-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathauth.service.ts
540 lines (447 loc) · 14.1 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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
import {
ConflictException,
Injectable,
Logger,
NotFoundException,
UnauthorizedException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { LoginUserInput } from 'src/user/dto/login-user.input';
import { RegisterUserInput } from 'src/user/dto/register-user.input';
import { User } from 'src/user/user.model';
import { In, Repository } from 'typeorm';
import { CheckTokenInput } from './dto/check-token.input';
import { JwtCacheService } from 'src/jwt-cache/jwt-cache.service';
import { Menu } from './menu/menu.model';
import { Role } from './role/role.model';
import { RefreshToken } from './refresh-token/refresh-token.model';
import { randomUUID } from 'crypto';
import { compare, hash } from 'bcrypt';
import {
EmailConfirmationResponse,
RefreshTokenResponse,
} from './auth.resolver';
import { MailService } from 'src/mail/mail.service';
@Injectable()
export class AuthService {
private readonly isMailEnabled: boolean;
constructor(
@InjectRepository(User)
private userRepository: Repository<User>,
private jwtService: JwtService,
private jwtCacheService: JwtCacheService,
private configService: ConfigService,
private mailService: MailService,
@InjectRepository(Menu)
private menuRepository: Repository<Menu>,
@InjectRepository(Role)
private roleRepository: Repository<Role>,
@InjectRepository(RefreshToken)
private refreshTokenRepository: Repository<RefreshToken>,
) {
// Read the MAIL_ENABLED environment variable, default to 'true'
this.isMailEnabled =
this.configService.get<string>('MAIL_ENABLED', 'false').toLowerCase() ===
'true';
}
async confirmEmail(token: string): Promise<EmailConfirmationResponse> {
try {
const payload = await this.jwtService.verifyAsync(token);
// Check if payload has the required email field
if (!payload || !payload.email) {
return {
message: 'Invalid token format',
success: false,
};
}
// Find user and update
const user = await this.userRepository.findOne({
where: { email: payload.email },
});
if (user && !user.isEmailConfirmed) {
user.isEmailConfirmed = true;
await this.userRepository.save(user);
return {
message: 'Email confirmed successfully!',
success: true,
};
}
return {
message: 'Email already confirmed or user not found.',
success: false,
};
} catch (error) {
return {
message: 'Invalid or expired token',
success: false,
};
}
}
async sendVerificationEmail(user: User): Promise<EmailConfirmationResponse> {
// Generate confirmation token
const verifyToken = this.jwtService.sign(
{ email: user.email },
{ expiresIn: '30m' },
);
// Send confirmation email
await this.mailService.sendConfirmationEmail(user.email, verifyToken);
// update user last time send email time
user.lastEmailSendTime = new Date();
await this.userRepository.save(user);
return {
message: 'Verification email sent successfully!',
success: true,
};
}
async resendVerificationEmail(email: string) {
const user = await this.userRepository.findOne({
where: { email },
});
if (!user) {
throw new Error('User not found');
}
if (user.isEmailConfirmed) {
return { message: 'Email already confirmed!' };
}
// Check if a cooldown period has passed (e.g., 1 minute)
const cooldownPeriod = 1 * 60 * 1000; // 1 minute in milliseconds
if (
user.lastEmailSendTime &&
new Date().getTime() - user.lastEmailSendTime.getTime() < cooldownPeriod
) {
const timeLeft = Math.ceil(
(cooldownPeriod -
(new Date().getTime() - user.lastEmailSendTime.getTime())) /
1000,
);
return {
message: `Please wait ${timeLeft} seconds before requesting another email`,
success: false,
};
}
return this.sendVerificationEmail(user);
}
async register(registerUserInput: RegisterUserInput): Promise<User> {
const { username, email, password, confirmPassword } = registerUserInput;
// Check for existing email
const existingUser = await this.userRepository.findOne({
where: { email },
});
if (password !== confirmPassword) {
throw new ConflictException('Passwords do not match');
}
const hashedPassword = await hash(password, 10);
// If the user exists but email is not confirmed and mail is enabled
if (existingUser && !existingUser.isEmailConfirmed && this.isMailEnabled) {
// Just update the existing user and resend verification email
existingUser.username = username;
existingUser.password = hashedPassword;
await this.userRepository.save(existingUser);
await this.sendVerificationEmail(existingUser);
return existingUser;
} else if (existingUser) {
throw new ConflictException('Email already exists');
}
let newUser;
if (this.isMailEnabled) {
newUser = this.userRepository.create({
username,
email,
password: hashedPassword,
isEmailConfirmed: false,
});
} else {
newUser = this.userRepository.create({
username,
email,
password: hashedPassword,
isEmailConfirmed: true,
});
}
await this.userRepository.save(newUser);
if (this.isMailEnabled) {
await this.sendVerificationEmail(newUser);
}
return newUser;
}
async login(loginUserInput: LoginUserInput): Promise<RefreshTokenResponse> {
const { email, password } = loginUserInput;
const user = await this.userRepository.findOne({
where: { email },
});
if (!user) {
throw new UnauthorizedException('Invalid credentials');
}
if (!user.isEmailConfirmed && this.isMailEnabled) {
throw new Error('Email not confirmed. Please check your inbox.');
}
const isPasswordValid = await compare(password, user.password);
if (!isPasswordValid) {
throw new UnauthorizedException('Invalid credentials');
}
const accessToken = this.jwtService.sign(
{ userId: user.id, email: user.email },
{ expiresIn: '30m' },
);
const refreshTokenEntity = await this.createRefreshToken(user);
this.jwtCacheService.storeAccessToken(accessToken);
return {
accessToken,
refreshToken: refreshTokenEntity.token,
};
}
private async createRefreshToken(user: User): Promise<RefreshToken> {
const token = randomUUID();
const sevenDays = 7 * 24 * 60 * 60 * 1000;
const refreshToken = this.refreshTokenRepository.create({
user,
token,
expiresAt: new Date(Date.now() + sevenDays), // 7 days
});
await this.refreshTokenRepository.save(refreshToken);
return refreshToken;
}
async validateToken(params: CheckTokenInput): Promise<boolean> {
try {
await this.jwtService.verifyAsync(params.token);
return this.jwtCacheService.isTokenStored(params.token);
} catch (error) {
Logger.log(error);
return false;
}
}
async logout(token: string): Promise<boolean> {
try {
await this.jwtService.verifyAsync(token);
const refreshToken = await this.refreshTokenRepository.findOne({
where: { token },
});
if (refreshToken) {
await this.refreshTokenRepository.remove(refreshToken);
}
return true;
} catch (error) {
return false;
}
}
async assignMenusToRole(roleId: string, menuIds: string[]): Promise<Role> {
// Find the role with existing menus
const role = await this.roleRepository.findOne({
where: { id: roleId },
relations: ['menus'],
});
if (!role) {
throw new NotFoundException(`Role with ID "${roleId}" not found`);
}
// Find all menus
const menus = await this.menuRepository.findByIds(menuIds);
if (menus.length !== menuIds.length) {
throw new NotFoundException('Some menus were not found');
}
if (!role.menus) {
role.menus = [];
}
const newMenus = menus.filter(
(menu) => !role.menus.some((existingMenu) => existingMenu.id === menu.id),
);
if (newMenus.length === 0) {
throw new ConflictException(
'All specified menus are already assigned to this role',
);
}
role.menus.push(...newMenus);
try {
await this.roleRepository.save(role);
Logger.log(
`${newMenus.length} menus assigned to role ${role.name} successfully`,
);
return await this.roleRepository.findOne({
where: { id: roleId },
relations: ['menus'],
});
} catch (error) {
Logger.error(`Failed to assign menus to role: ${error.message}`);
throw error;
}
}
async removeMenuFromRole(roleId: string, menuId: string): Promise<Role> {
const role = await this.roleRepository.findOne({
where: { id: roleId },
relations: ['menus'],
});
if (!role) {
throw new NotFoundException(`Role with ID "${roleId}" not found`);
}
const menuIndex = role.menus?.findIndex((menu) => menu.id === menuId);
if (menuIndex === -1) {
throw new NotFoundException(
`Menu with ID "${menuId}" not found in role "${role.name}"`,
);
}
role.menus.splice(menuIndex, 1);
try {
await this.roleRepository.save(role);
Logger.log(`Menu removed from role ${role.name} successfully`);
return await this.roleRepository.findOne({
where: { id: roleId },
relations: ['menus'],
});
} catch (error) {
Logger.error(`Failed to remove menu from role: ${error.message}`);
throw error;
}
}
async assignRoles(userId: string, roleIds: string[]): Promise<User> {
const user = await this.userRepository.findOne({
where: { id: userId },
relations: ['roles'],
});
if (!user) {
throw new NotFoundException(`User with ID "${userId}" not found`);
}
const roles = await this.roleRepository.findBy({ id: In(roleIds) });
if (roles.length !== roleIds.length) {
throw new NotFoundException('Some roles were not found');
}
if (!user.roles) {
user.roles = [];
}
const newRoles = roles.filter(
(role) => !user.roles.some((existingRole) => existingRole.id === role.id),
);
if (newRoles.length === 0) {
throw new ConflictException(
'All specified roles are already assigned to this user',
);
}
user.roles.push(...newRoles);
try {
await this.userRepository.save(user);
Logger.log(
`${newRoles.length} roles assigned to user ${user.username} successfully`,
);
return await this.userRepository.findOne({
where: { id: userId },
relations: ['roles'],
});
} catch (error) {
Logger.error(`Failed to assign roles to user: ${error.message}`);
throw error;
}
}
async removeRoleFromUser(userId: string, roleId: string): Promise<User> {
const user = await this.userRepository.findOne({
where: { id: userId },
relations: ['roles'],
});
if (!user) {
throw new NotFoundException(`User with ID "${userId}" not found`);
}
const roleIndex = user.roles?.findIndex((role) => role.id === roleId);
if (roleIndex === -1) {
throw new NotFoundException(
`Role with ID "${roleId}" not found in user's roles`,
);
}
user.roles.splice(roleIndex, 1);
try {
await this.userRepository.save(user);
Logger.log(`Role removed from user ${user.username} successfully`);
return await this.userRepository.findOne({
where: { id: userId },
relations: ['roles'],
});
} catch (error) {
Logger.error(`Failed to remove role from user: ${error.message}`);
throw error;
}
}
async getUserRolesAndMenus(userId: string): Promise<{
roles: Role[];
menus: Menu[];
}> {
const user = await this.userRepository.findOne({
where: { id: userId },
relations: ['roles', 'roles.menus'],
});
if (!user) {
throw new NotFoundException(`User with ID "${userId}" not found`);
}
const userRoles = user.roles || [];
// Get unique menus across all roles
const userMenus = Array.from(
new Map(
userRoles
.flatMap((role) => role.menus || [])
.map((menu) => [menu.id, menu]),
).values(),
);
return {
roles: userRoles,
menus: userMenus,
};
}
async getUserRoles(userId: string): Promise<{
roles: Role[];
}> {
const user = await this.userRepository.findOne({
where: { id: userId },
relations: ['roles'],
});
if (!user) {
throw new NotFoundException(`User with ID "${userId}" not found`);
}
return {
roles: user.roles || [],
};
}
async getUserMenus(userId: string): Promise<{
menus: Menu[];
}> {
const user = await this.userRepository.findOne({
where: { id: userId },
relations: ['roles', 'roles.menus'],
});
if (!user) {
throw new NotFoundException(`User with ID "${userId}" not found`);
}
const userMenus = Array.from(
new Map(
(user.roles || [])
.flatMap((role) => role.menus || [])
.map((menu) => [menu.id, menu]),
).values(),
);
return {
menus: userMenus,
};
}
/**
* refresh access token base on refresh token.
* @param refreshToken refresh token
* @returns return new access token and refresh token
*/
async refreshToken(refreshToken: string): Promise<RefreshTokenResponse> {
const existingToken = await this.refreshTokenRepository.findOne({
where: { token: refreshToken },
relations: ['user'],
});
if (!existingToken || existingToken.expiresAt < new Date()) {
throw new UnauthorizedException('Invalid refresh token');
}
const accessToken = this.jwtService.sign(
{
userId: existingToken.user.id,
email: existingToken.user.email,
},
{ expiresIn: '30m' },
);
this.jwtCacheService.storeAccessToken(accessToken);
return {
accessToken,
refreshToken: refreshToken,
};
}
}