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
88import {
BadRequestException,
Injectable,
Logger,
NotFoundException,
UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import * as bcrypt from 'bcrypt';
import { Users } from 'src/entities/Users';
import { JwtPayload } from './jwt/jwt-payload.interface';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
@Injectable()
export class AuthService {
constructor(
@InjectRepository(Users)
private userRepository: Repository<Users>,
private jwtService: JwtService,
) {}
private readonly logger = new Logger('AuthSeviceLogger');
async validateUser(email: string, password: string): Promise<Users> {
const user = await this.userRepository.findOne({
where: { email },
select: ['id', 'nickname', 'role', 'email', 'password'],
});
if (!user) {
throw new NotFoundException('์์ด๋๋ฅผ ํ์ธํด์ฃผ์ธ์.');
}
const isPasswordValidated = await bcrypt.compare(password, user.password);
if (!isPasswordValidated) {
throw new BadRequestException('์์ด๋์ ๋น๋ฐ๋ฒํธ๋ฅผ ํ์ธํด์ฃผ์ธ์.');
}
return user;
}
async tokenValidateUser(payload: JwtPayload) {
return await this.userRepository.findOne({ where: { id: payload.id } });
}
async generateTokens(user: Users) {
const payload = {
id: user.id,
email: user.email,
nickname: user.nickname,
role: user.role,
};
try {
const accessToken = await this.jwtService.sign(payload);
const refreshToken = await this.jwtService.sign(payload, {
secret: process.env.JWT_REFRESH_SECRET,
expiresIn: process.env.JWT_REFRESH_EXPIRATION_TIME,
});
return { accessToken, refreshToken };
} catch (error) {
throw new UnauthorizedException(`๋ก๊ทธ์ธ ์คํจ error: ${error}`);
}
}
async refreshToken(token: string) {
try {
const payload = await this.jwtService.verify(token, {
secret: process.env.JWT_REFRESH_SECRET,
});
const newPayload = {
id: payload.id,
email: payload.email,
nickname: payload.nickname,
};
return {
accessToken: await this.jwtService.sign(newPayload),
refreshToken: await this.jwtService.sign(newPayload, {
secret: process.env.JWT_REFRESH_SECRET,
expiresIn: process.env.JWT_REFRESH_EXPIRATION_TIME,
}),
};
} catch (error) {
throw new UnauthorizedException(
'ํ ํฐ์ด ์ ํจํ์ง ์๊ฑฐ๋, ๋ง๋ฃ๋ ํ ํฐ์
๋๋ค.',
);
}
}
}