-
Notifications
You must be signed in to change notification settings - Fork 230
/
Copy pathauth.service.ts
69 lines (57 loc) · 1.9 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
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import type { JwtPayload, JwtSign, Payload } from './auth.interface';
import { User, UserService } from '../shared/user';
@Injectable()
export class AuthService {
constructor(
private jwt: JwtService,
private user: UserService,
private config: ConfigService,
) {}
public async validateUser(username: string, password: string): Promise<User | null> {
const user = await this.user.fetch(username);
if (user.password === password) {
// eslint-disable-next-line sonarjs/sonar-no-unused-vars
const { password: pass, ...result } = user;
return result;
}
return null;
}
public validateRefreshToken(data: Payload, refreshToken: string): boolean {
if (!this.jwt.verify(refreshToken, { secret: this.config.get('jwtRefreshSecret') })) {
return false;
}
const payload = this.jwt.decode<{ sub: string }>(refreshToken);
return payload.sub === data.userId;
}
public jwtSign(data: Payload): JwtSign {
const payload: JwtPayload = { sub: data.userId, username: data.username, roles: data.roles };
return {
access_token: this.jwt.sign(payload),
refresh_token: this.getRefreshToken(payload.sub),
};
}
public getPayload(token: string): Payload | null {
try {
const payload = this.jwt.decode<JwtPayload | null>(token);
if (!payload) {
return null;
}
return { userId: payload.sub, username: payload.username, roles: payload.roles };
} catch {
// Unexpected token i in JSON at position XX
return null;
}
}
private getRefreshToken(sub: string): string {
return this.jwt.sign(
{ sub },
{
secret: this.config.get('jwtRefreshSecret'),
expiresIn: '7d', // Set greater than the expiresIn of the access_token
},
);
}
}