34 lines
1009 B
TypeScript
34 lines
1009 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) {
|
|
const user = await this.usersService.findOneByUsername(username);
|
|
if (!user) {
|
|
throw new UnauthorizedException('User not found');
|
|
}
|
|
const isMatch = await bcrypt.compare(password, user.password);
|
|
if (!isMatch) {
|
|
throw new UnauthorizedException('Invalid password');
|
|
}
|
|
const { password: _, ...rest } = user;
|
|
return rest;
|
|
}
|
|
|
|
async login(user: any) {
|
|
const payload = { username: user.username, sub: user.id };
|
|
console.log("access_token:", payload);
|
|
return {
|
|
access_token: this.jwtService.sign(payload),
|
|
};
|
|
}
|
|
}
|