auth.service.ts
2.02 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
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 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;
}
}