29 lines
861 B
TypeScript
29 lines
861 B
TypeScript
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
|
import { JwtService } from '@nestjs/jwt';
|
|
import { UsersService } from '../users/users.service';
|
|
import * as bcrypt from 'bcrypt';
|
|
|
|
@Injectable()
|
|
export class AuthService {
|
|
constructor(
|
|
private usersService: UsersService,
|
|
private jwtService: JwtService
|
|
) {}
|
|
|
|
async validateUser(username: string, password: string): Promise<any> {
|
|
const user = await this.usersService.findOneByUsername(username);
|
|
if (user && (await bcrypt.compare(password, user.password))) {
|
|
const { password, ...result } = user;
|
|
return result;
|
|
}
|
|
throw new UnauthorizedException('Invalid username or password');
|
|
}
|
|
|
|
async login(user: any) {
|
|
const payload = { username: user.username, sub: user.id };
|
|
return {
|
|
access_token: this.jwtService.sign(payload),
|
|
};
|
|
}
|
|
}
|