-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.service.ts
More file actions
47 lines (36 loc) · 1.1 KB
/
auth.service.ts
File metadata and controls
47 lines (36 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import { Injectable } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { UsersService } from "../users/users.service";
import * as bcrypt from "bcryptjs";
import { UnauthorizedException } from "@nestjs/common";
@Injectable()
export class AuthService {
constructor(
private readonly usersService: UsersService,
private readonly jwtService: JwtService
) {}
async validateUser(email: string, password: string) {
const user = await this.usersService.findByEmail(email);
if (!user) return null;
const passwordValid = await bcrypt.compare(password, user.password);
if (!passwordValid) return null;
const { password: _, ...result } = user;
return result;
}
async login(email: string, password: string) {
const user = await this.validateUser(email, password);
if (!user) {
throw new UnauthorizedException("Credenciais inválidas");
}
const payload = {
sub: user.id,
email: user.email,
role: user.role,
};
const token = this.jwtService.sign(payload);
return {
access_token: token,
user,
};
}
}