-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.service.ts
More file actions
131 lines (108 loc) · 3.81 KB
/
auth.service.ts
File metadata and controls
131 lines (108 loc) · 3.81 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
import { User } from "@modules/User/entity/user.entity";
import { CreateUserDto } from "./dto/create-user.dto";
import { LoginUserDto } from "./dto/login.dto";
import { hashPassword, comparePasswords } from "@lib/utils"
import { ErrorEnum } from "@lib/enums";
import { env } from "@shared/env";
import jwt from "jsonwebtoken"
import { Email } from "@core/abstractions/email";
import { MailOptions } from "@lib/types";
import { resetPasswordTemplate, welcomeTemplate } from "./email/template";
import { Repository } from "typeorm";
export class AuthService {
constructor(
private readonly authRepository: Repository<User>,
private readonly emailService: Email<MailOptions>
) { }
async register(createUserDTO: CreateUserDto): Promise<User> {
const isAlreadyRegistered = await this.authRepository.findOne({ where: { email: createUserDTO.email } });
if (isAlreadyRegistered) {
throw new Error(ErrorEnum.USER_ALREADY_EXISTS.message);
}
const password_digest = await hashPassword(createUserDTO.password);
const user = await this.authRepository.save({...createUserDTO, password: password_digest });
this.emailService.send({
to: user.email,
subject: "Welcome to Payment Records",
from: process.env.EMAIL_USER,
html: welcomeTemplate(user.name)
})
console.debug("Mensagem enviada");
return user;
}
async login(LoginUserDto: LoginUserDto) {
const user = await this.authRepository.findOne({ where: { email: LoginUserDto.email } });
if (!user) {
throw new Error(ErrorEnum.INVALID_CREDENTIALS.message);
}
const isValidPassword = await comparePasswords(LoginUserDto.password, user.password);
if (!isValidPassword) {
throw new Error(ErrorEnum.INVALID_CREDENTIALS.message);
};
const access_token = jwt.sign(
{
email: user.email,
id: user.id
}, env.ACCESS_SECRET,
{ expiresIn: env.ACCESS_EXPIRE as number })
const refresh_token = jwt.sign({
id: user.id
}, env.REFRESH_SECRET,
{
expiresIn: env.REFRESH_EXPIRE as number
})
return {
...user,
access_token,
refresh_token
}
}
async refreshToken(refreshToken: string) {
const decoded = jwt.verify(refreshToken, env.REFRESH_SECRET);
if (!decoded) throw new Error(ErrorEnum.UNAUTHORIZED.message);
const newAccessToken = jwt.sign(
{
id: (decoded as { id: string }).id
},
env.ACCESS_SECRET,
{ expiresIn: env.ACCESS_EXPIRE as number }
);
return {
access_token: newAccessToken
};
}
logout() {
return;
}
async forgotPassword(email: string) {
const user = await this.authRepository.findOne({ where: { email } });
if (!user) throw new Error(ErrorEnum.NOT_FOUND.message);
const resetToken = jwt.sign(
{ id: user.id },
env.RESET_SECRET,
{ expiresIn: env.RESET_EXPIRE as number }
);
try {
this.emailService.send({
to: user.email,
subject: "Password Reset",
from: process.env.EMAIL_USER,
html: resetPasswordTemplate(resetToken, user.name),
messageId: resetToken
})
return { message: "Password reset email sent" }
} catch {
throw new Error(ErrorEnum.INTERNAL_SERVER_ERROR.message);
}
}
async resetPassword(token: string, newPassword: string) {
const decoded = jwt.verify(token, env.RESET_SECRET);
if (!decoded) throw new Error(ErrorEnum.UNAUTHORIZED.message);
const userId = (decoded as { id: string }).id;
const user = await this.authRepository.findOne({ where: { id: userId } });
if (!user) throw new Error(ErrorEnum.NOT_FOUND.message);
const hashedPassword = await hashPassword(newPassword);
await this.authRepository.update(userId, { password: hashedPassword });
return { message: "Password updated successfully" };
}
}