-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
auth.service.ts
245 lines (220 loc) · 6.15 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
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import {
ConflictException,
HttpStatus,
Injectable,
Logger,
NotFoundException,
UnauthorizedException,
} from "@nestjs/common";
import { LoginDto, SignupDto, VerifyAccountDto } from "./auth.dto";
import prisma from "../../common/database/primsa";
import { VerificationCodeService } from "../../utils/verification-code/verification-code.service";
import { compare, genSalt, hash } from "bcrypt";
import { MailerService } from "../../utils/mailer/mailer.service";
import path from "path";
import { Prisma, User } from "@prisma/client";
import { ErrorService } from "../../utils/error/error.service";
import { JwtService } from "@nestjs/jwt";
import { ConfigService } from "@nestjs/config";
@Injectable()
export class AuthService {
constructor(
private readonly verificationCodeService: VerificationCodeService,
private readonly mailerService: MailerService,
private readonly errorService: ErrorService,
private readonly jwtService: JwtService,
private readonly configService: ConfigService,
) {}
logger: Logger = new Logger("AuthService", { timestamp: true });
/**
* Create a new user in the database and send a verification email
* @param signupDto Details of the user to be created
*/
async postSignup(signupDto: SignupDto) {
const hashedPassword = await this.hashPassword(signupDto.password);
const verificationCode = this.verificationCodeService.generateCode();
const createdUser = await prisma.user.create({
data: {
name: signupDto.name,
email: signupDto.email,
username: signupDto.username,
password: hashedPassword,
verification_code: verificationCode,
},
});
// send verification email
await this.mailerService.sendEmail(
signupDto.email,
"Welcome to maya, please verify you'r email",
this.emailTemplate(signupDto.name, verificationCode),
[
{
filename: "logo",
path: path.resolve("./assets/logos/full.png"),
cid: "logo",
},
{
filename: "banner",
path: path.resolve("./assets/logos/banner.png"),
cid: "banner",
},
],
);
return Promise.resolve(createdUser);
}
/**
* Verify the user after signup
* @param params params from the request
*/
async getVerifyAccount(params: VerifyAccountDto) {
const user = await prisma.user.findUniqueOrThrow({ where: { email: params.email } });
if (user.verification_code !== +params.verification_code) {
return Promise.reject(
this.errorService.serviceAPIError(
"Invalid verification code",
HttpStatus.UNAUTHORIZED,
),
);
}
return await prisma.user.update({
where: { email: params.email },
data: { verified: true, verification_code: 0 },
});
}
/**
* Create access and refresh tokens for the user
*
* also creates a session in database
*/
async postLogin(loginDto: LoginDto) {
/*
TODO:
- generate access and refresh tokens
- create a session in database
- return the tokens
*/
let user: User;
// check if input is email or username
const isEmail = loginDto.email_username.includes("@");
if (isEmail) {
// find user with email
user = await prisma.user.findUniqueOrThrow({
where: {
email: loginDto.email_username,
},
});
} else {
// find user with username
user = await prisma.user.findUniqueOrThrow({
where: {
username: loginDto.email_username,
},
});
}
if (!user.verified) {
return Promise.reject(
this.errorService.serviceAPIError("User not verified", HttpStatus.FORBIDDEN),
);
}
// check if password is correct
const isPasswordCorrect = await compare(loginDto.password, user.password);
if (!isPasswordCorrect) {
return Promise.reject(
this.errorService.serviceAPIError("Invalid password", HttpStatus.UNAUTHORIZED),
);
}
this.createAccessAndRefreshTokens(user);
return user;
}
/**
* Creates access and refresh tokens for the user
* @param user The user for which the tokens are to be created
*/
async createAccessAndRefreshTokens(user: User) {
const accessTokenPublicKey = this.configService.get<string>("ACCESS_TOKEN_PUBLIC_KEY");
const refreshTokenPublicKey = this.configService.get<string>("REFRESH_TOKEN_PUBLIC_KEY");
// create a session in database
const session = prisma.session.create({
data: {
user_id: user.id,
},
});
// create access and refresh tokens
const accessToken = this.jwtService.signAsync(String(user.id), {
secret: accessTokenPublicKey,
expiresIn: "15m",
});
}
/**
* Hash a password
* @param password The password to be hashed
*
* @example
* ```ts
* const hashedPassword = await this.authService.hashPassword("password");
* ```
*/
async hashPassword(password: string): Promise<string> {
const salt = await genSalt(10);
return await hash(password, salt);
}
/**
* Template for the email that will be sent to the user
* on signup and this will contain the verification code
*
* @param name name of user to which email is to be sent
* @param verificationCode the verification code to be sent
*/
emailTemplate(name: string, verificationCode: number) {
// eslint-disable-next-line no-secrets/no-secrets
return `
<img src="cid:banner" alt="banner" style="
display: block; margin-left: auto; margin-right: auto;
height: 350px;
width: 50vw;
text-align: center;
margin-top: 0;
margin-bottom: 0;
" />
<h1
style="text-align: center;"
>
Welcome To maya!
</h1>
<img
style="display: block; margin-left: auto; margin-right: auto; margin-top: 0; width: 20%"
src="cid:logo"
alt="Logo"
/>
<p style="margin-top: 0; font-size: medium; text-align: center">
Dear ${name}, <br />
<br />
Thank you for registering. Please enter this OTP in maya
</p>
<p style="text-align: center; margin-top: 0;">
<a
href="#"
style="
text-align: center;
display: flex;
width: 7%;
padding: 10px 20px;
background-color: #56baa7;
text-decoration: none;
border-radius: 5px;
font-size: medium;
color: #ffffff;
justify-content: center;
margin-left: auto;
margin-right: auto;
"
>${verificationCode}</a
>
</p>
<p style="text-align: center; color: #888888">
If you did not register on our site, please ignore this email.
<br />Regards, <br />maya
</p>
`;
}
}