auth.service.ts
2.57 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
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
import type { UserEntity } from '@/models/entity/user.entity';
import type { JwtConfig } from '@/types';
import { UsersService } from '@/modules/users/users.service';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import bcrypt from 'bcryptjs';
@Injectable()
export class AuthService {
constructor(
private usersService: UsersService,
private jwtService: JwtService,
private configService: ConfigService,
) {}
/**
* get user info
* @param username
*/
async getAccessCodes(username: string): Promise<string[]> {
const user = await this.usersService.findOne(username);
const mockCodes = [
// super
{
codes: ['AC_100100', 'AC_100110', 'AC_100120', 'AC_100010'],
userId: 0,
},
{
// admin
codes: ['AC_100010', 'AC_100020', 'AC_100030'],
userId: 1,
},
{
// user
codes: ['AC_1000001', 'AC_1000002'],
userId: 2,
},
];
return mockCodes.find((item) => item.userId === user.id)?.codes ?? [];
}
async getUserInfo(username: string): Promise<Omit<UserEntity, 'password'>> {
const user = await this.usersService.findOne(username);
const { password: _pass, ...userInfo } = user;
return userInfo;
}
/**
* user login
*/
async login(userEntity: UserEntity): Promise<any> {
const { id, roles, username } = userEntity;
const payload = { id, roles, username };
const { refreshSecret, refreshexpiresIn } =
this.configService.get<JwtConfig>('jwt');
return {
accessToken: await this.jwtService.signAsync(payload),
refreshToken: this.jwtService.sign(payload, {
expiresIn: refreshexpiresIn,
secret: refreshSecret,
}),
};
}
async refresh(refreshToken: string) {
try {
const payload = this.jwtService.verify(refreshToken, {
secret: this.configService.get<JwtConfig>('jwt').refreshSecret,
});
const user = await this.usersService.findOne(payload.username);
if (!user) {
throw new UnauthorizedException();
}
return this.login(user);
} catch {
throw new UnauthorizedException();
}
}
async validateUser(username: string, password: string): Promise<any> {
const user = await this.usersService.findOne(username);
if (user && (await bcrypt.compare(password, user.password))) {
// 使用 bcrypt.compare 验证密码
const { password: _pass, ...result } = user;
return result;
}
return null;
}
}