-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathauth.service.ts
97 lines (80 loc) · 2.57 KB
/
auth.service.ts
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import { ForbiddenException, Injectable, UnauthorizedException } from '@nestjs/common';
import { LoggerService } from '../common/service/logger.service';
import { UserService } from '../users/users.service';
import { JwtService } from '@nestjs/jwt';
import * as bcrypt from 'bcrypt';
import { jwtConstants } from '../auth/constants';
import { v4 as uuid } from 'uuid';
import { sendResponse } from 'src/utils';
@Injectable()
export class AuthService {
constructor(
private usersService: UserService,
private jwtService: JwtService,
private readonly logger: LoggerService
) { }
async signIn(email: string, pass: string) {
const id: string = uuid();
this.logger.log('auth service api called', id, 'auth.service.ts', '', '', 'signIn-service');
const user = await this.usersService.findOneUser(email);
console.log(user)
if (!user) {
throw new UnauthorizedException('Username and password wrong.');
}
const match = await bcrypt.compare(pass, user?.password);
console.log(match)
if (match) {
const payload = { email: user.email, userId: user._id.toString(), username: user.username };
const tokens = await this.getTokens(payload);
return {
...tokens
};
} else {
throw new UnauthorizedException('Username and password wrong.');
}
}
async refreshTokens(userId: string, rt: string) {
const user = await this.usersService.findOne(userId);
if (!user || !user.hashdRt) throw new ForbiddenException('Access Denied.');
const rtMatches = await bcrypt.compare(rt, user.hashdRt);
if (!rtMatches) throw new ForbiddenException('Access Denied.');
const tokens = await this.getTokens(user);
const rtHash = await this.hashPassword(tokens.refresh_token);
await this.usersService.updateOne(user._id, { hashdRt: rtHash });
return tokens;
}
async getTokens(user: any) {
const [at, rt] = await Promise.all([
this.jwtService.signAsync(
{
sub: user.userId,
email: user.email,
username: user.username
},
{
secret: jwtConstants.secret,
expiresIn: '24h',
},
),
this.jwtService.signAsync(
{
sub: user.userId,
email: user.email,
username: user.username
},
{
secret: jwtConstants.secret,
expiresIn: '30d',
},
),
]);
return {
access_token: at,
refresh_token: rt,
};
}
//Encriptación de la copntraseña
async hashPassword(data: string) {
return bcrypt.hash(data, 10);
}
}