Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 | 7x 7x 7x 112x 112x 490x 112x 7x 7x 7x 336x 7x 160x 76x 159x 1x 235x 76x 7x 21x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 18x 18x 18x 18x 1x 17x 17x 15x 1x 1x 14x 14x 14x 14x 14x 14x 14x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 14x 14x 14x 14x 13x 13x 5x 13x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 1x 2x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 14x 14x 14x 8x 14x 1x 1x 1x 1x 1x 2x 2x 2x 2x 3x 3x 3x 3x 1x 2x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x | import HttpStatusCode from '@/utils/HTTPStatusCodes';
import { generateAccessToken, generateRefreshToken } from '@/utils/jwtHandler';
import { ApiResponseBody, ResponseHandler } from '@/utils/responseHandler';
import { logger } from '@/utils/winston';
import { Otps, User } from '@prisma/client';
import bcrypt from 'bcryptjs';
import { v4 as uuidv4 } from 'uuid';
import prisma from '@/services/prisma.service';
import appConfig, { parseStrPeriod, TimeMap } from '@/config/app.config';
import { addTime } from '@/utils/helpers';
import { apiMethod } from '@/decorators/api.decorator';
import { Auth, AuthClass } from '@/decorators/auth.decorator';
import { VerifyEmailMailer } from '@/messager/verify-email.mailer';
import { UpdatePasswordMailer } from '@/messager/update-password.mailer';
import { ResetPasswordMailer } from '@/messager/reset-password.mailer';
import { OTPHandler } from '@/utils/otpHandler';
import { parseUserPayload } from '@/utils/parsers';
import { MFAEmailMailer } from '@/messager/mfa-email.mailer';
import { MFAMessageMailer } from '@/messager/mfa-sms.sms';
impoIrt {
PermissionManager,
PermissionPayload,
PermissionRole,
} from '../services/permissions.service';
E
export class AuthRepository extends AuthClass {
@apiMethod<IAuthResponse>()
static async loginUser(payload: TAuthSchema): Promise<ApiResponseBody<IAuthResponse>> {
const resBody = (this as any).getResBody();
const user = await prisma.user.findUnique({
where: {
I email: payload.email,
},
});
if (!user) {
return ResponseHandler.Unauthorized('Credentials Error');
}
const isValidPassword = await bcrypt.compare(payload.password, user.password);
if (isValidPassword) {
if (user.enableMFA) {
resBody.data = {
mfa: true,
user: parseUserPayload(user),
};
return resBody;
}
const token = generateAccessToken(user.id);
const refreshToken = generateRefreshToken();
await prisma.refreshToken.create({
data: {
token: refreshToken,
userId: user.id,
expiresAt: addTime(30, 'd'),
},
});
const accessToken = {
token: token,
refreshToken: refreshToken,
};
const responseData = {
accessToken: accessToken,
user: parseUserPayload(user),
};
resBody.data = responseData;
return resBody;
} else {
return ResponseHandler.Unauthorized('Password not match');
}
}
@apiMethod<IAuthResponse>()
static async sendMFARequest(
payload: TSendMFARequestSchema
): Promise<ApiResponseBody<IStatusResponse>> {
const resBody: ApiResponseBody<IStatusResponse> = (this as any).getResBody();
const user = await prisma.user.findUnique({
where: {
id: payload.userId,
},
include: {
otp: true,
},
});
if (!user) {
return ResponseHandler.NotFound('User not found');
}
if (user.enableMFA === false) {
return ResponseHandler.BadRequest('MFA is not enabled for this user');
}
resBody.data = await this.sendMFAOtp(user, payload);
return resBody;
}
@apiMethod<IAuthResponse>()
static async confirmMFARequest(
payload: TConfirmMFASchema
): Promise<ApiResponseBody<IAuthResponse>> {
const resBody = (this as any).getResBody();
const isValidOTP = await OTPHandler.validateOTP(payload.userId, payload.otp);
if (!isValidOTP) {
return ResponseHandler.Forbidden('Invalid or expired OTP');
}
const user = await prisma.user.findUnique({
where: {
id: payload.userId,
},
});
if (!useIr) {
return ResponseHandler.NotFound('User not found');
}
I
const token = generateAccessToken(payload.userId);
const refreshToken = generateRefreshToken();
await prisma.refreshToken.create({
data: {
token: refreshToken,
userId: payload.userId,
expiresAt: addTime(30, 'd'),
},
});
const acIcessToken = {
token: token,
refreshToken: refreshToken,
};
const responseData = {
accessToken: accessToken,
user: parseUserPayload(user),
};I
resBody.data = responseData;
return resBody;
}
@apiMethod<IRefreshTokenResponse>()
static async refreshToken({
refreshToken,
}: TRefreshTokenSchema): Promise<ApiResponseBody<IRefreshTokenResponse>> {
const resBody = (this as any).getResBody();
const storedToken = await prisma.refreshToken.findUnique({
where: { token: refreshToken },
});
if (!storedToken || new Date() > storedToken.expiresAt) {
return ResponseHandler.Unauthorized('Invalid or expired refresh token');
}
const newAccessToken = generateAccessToken(storedToken.userId);
const newRefreshToken = generateRefreshToken();
await prisma.refreshToken.update({
where: { token: refreshToken },
data: {
token: newRefreshToken,
expiresAt: addTime(30, 'd'),
},
});
I
resBody.data = { accessToken: newAccessToken, refreshToken: newRefreshToken };
return resBody;
}
@apiMethod<IUser>()
static async createUser(payload: TRegisterSchema): Promise<ApiResponseBody<IUser>> {
const resBody = (this as any).getResBody();
const role = await this.handleRole(
payload.type === 'DOCTOR'
? PermissionRole.DOCTOR
: payload.type === 'PATIENT'
? PermissionRole.PATIENT
: PermissionRole.ADMIN
);
const user = await prisma.user.create({
data: {
email: payload.email,
phone: payload.phone,
name: payload.name,
password: bcrypt.hashSync(payload.password, 10),
userType: payload.type,
role: {
connect: {
id: role.id,
},
},
},
});
resBody.data = {
id: user.id,
email: user.email,
phone: user.phone,
name: user.name,
verifiedEmail: user.verifiedEmail,
userType: user.userType,
createdAt: user.createdAt,
updatedAt: user.updatedAt,
};
if (appConfig.requireVerifyEmail) {
await this.sendEmailVerification(user);
}
return resBody;
}
@apiMethod<IStatusResponse>()
static async forgotPassword(
payload: TForgetPasswordSchema
): Promise<ApiResponseBody<IStatusResponse>> {
const resBody = (this as any).getResBody();
const user = await prisma.user.findUnique({
where: {
email: payload.email,
userType: payload.type,
},
});
if (!user) {
return ResponseHandler.NotFound('User not found');
}
const token = uuidv4();
await prisma.resetPasswordToken.create({
data: {
token,
userId: user.id,
expiresAt: addTime(30, 'm'),
},
});E
if (user) {
new ResetPasswordMailer([user.email])
.generate({
name: user.name,
verificationLink: `${process.env.RESET_PASSWORD_UI_URL}/${token}`,
})
.then((instance) => {
instance.sendEmail();
});
}
resBody.data = {
status: true,
};
return resBody;
}
@apiMethod<IStatusResponse>()
static async resetPassword(
payload: TResetPasswordSchema
): Promise<ApiResponseBody<IStatusResponse>> {
const resBody = (this as any).getResBody();
const token = await prisma.resetPasswordToken.findUnique({
where: {
token: payload.token,
expiresAt: {
gte: new Date(),
},
},
include: {
user: true,
},
});
if (!token) {
return ResponseHandler.Forbidden('Invalid or expired token');
}
const hashedPassword = await bcrypt.hash(payload.newPassword, 10);
await prisma.user.update({
where: {
id: token.userId,
},
data: {
password: hashedPassword,
},
});
await prisma.resetPasswordToken.delete({
where: {
token: payload.token,
},
});
resBody.data = {
status: true,
};
return resBody;
}I
@Auth
@apiMethod<IStatusResponse>()
static async updatePassword(
payload: TUpdatePasswordSchema
): Promise<ApiResponseBody<IStatusResponse>> {
const userId = this.USER.userId;
const resBody = (this as any).getResBody();
const user = await prisma.user.findUnique({
where: {
id: userId,
},
});
if (!user) {
resBody.error = {
code: HttpStatusCode.NOT_FOUND,
message: 'User not found',
};
return resBody;
}
const isValidPassword = await bcrypt.compare(payload.oldPassword, user.password);
if (!isValidPassword) {
return ResponseHandler.Unauthorized('Invalid old password');
}
if (appConfig.updatePasswordRequireVerification) {
await this.sendConfirmPasswordUpdate(user, payload.newPassword);
} else {
const hashedPassword = await bcrypt.hash(payload.newPassword, 10);
await prisma.user.update({
where: {
id: userId,
},
data: {
paIssword: hashedPassword,
},
});
}
resBody.data = {
status: true,
};
return resBody;
}
@apiMethod<IStatusResponse>()
static async confirmUpdatePassword(
payload: TValidateUserSchema
): Promise<ApiResponseBody<IStatusResponse>> {
const resBody = (this as any).getResBody();
const token = await prisma.updatePasswordToken.findUnique({
where: {
token: payload.token,
},
});
if (!token) {
return ResponseHandler.Forbidden('Invalid or expired token');
}
await prisma.user.update({
where: {
id: token.userId,
},
data: {
password: token.newPassword,
},
});
await prisma.updatePasswordToken.delete({
where:I {
token: payload.token,
},
});
resBody.data = {
status: true,
};
return resBody;
}
@apiMethod<IStatusResponse>()
static async verifyUser(payload: TValidateUserSchema): Promise<ApiResponseBody<IStatusResponse>> {
const resBody = (this as any).getResBody();
const token = await prisma.verifyEmailToken.findUnique({
where: {
token: payload.token,
expiresAt: {
gte: new Date(),
},
},
include: {
user: true,
},
});
if (!token) {
return ResponseHandler.Forbidden('Invalid or expired token');
}
await prisma.user.update({
where: {
id: token.userId,
},I
data: {
verifiedEmail: true,
},
});
await prisma.verifyEmailToken.delete({
where: {
token: payload.token,
},
});
resBody.data = {
status: true,
};
I
return resBody;
}
@Auth
@apiMethod<IStatusResponse>()
static async verifyUserPhoneNumber(): Promise<ApiResponseBody<IStatusResponse>> {
const resBody = (this as any).getResBody();
const userId = this.USER.userId;
const user = await prisma.user.findUnique({
where: {
id: userId,
},
include: {
otp: true,
},
});
if (!user) {
return ResponseHandler.NotFound('User not found');
}
resBody.data = await this.sendMFAOtp(user, {
method: 'phone',
userId: userId,
});
return resBody;
}
@Auth
@apiMethod<IStatusResponse>()
static async confirmUserPhoneNumber(
payload: TValidateOTPSchema
): Promise<ApiResponseBody<IStatusResponse>> {
const resBody = (this as any).getResBody();
const userId = this.USER.userId;
const isIValidOTP = await OTPHandler.validateOTP(userId, payload.otp);
if (!isValidOTP) {
returnI ResponseHandler.Forbidden('Invalid or expired OTP');
}
await prIisma.user.update({
where: {
id: userId,
},
data: {
verifiedPhoneNumber: true,
},
});
resBody.data = {
status: true,
};
return resBody;
}
@Auth
@apiMethod<IStatusResponse>()
static async confirm2faOtp(
payload: TValidateOTPSchema
): Promise<ApiResponseBody<IStatusResponse>> {
const resBody = (this as any).getResBody();
const userId = this.USER.userId;
const isValidOTP = await OTPHandler.validateOTP(userId, payload.otp);
if (!isValidOTP) {
return ResponseHandler.Forbidden('Invalid or expired OTP');
}
resBody.data = {
status: true,
};
return resBody;
}
@Auth
@apiMethod<IStatusResponse>()
static async enableMFA(): Promise<ApiResponseBody<IStatusResponse>> {
const resBody: ApiResponseBody<IStatusResponse> = (this as any).getResBody();
const userId = this.USER.userId;
const user = await prisma.user.findUnique({
where: { id: userId },
});
if (!user) {
return ResponseHandler.NotFound('User not found');
}
if (!user.verifiedEmail) {
return ResponseHandler.Unauthorized('Email must be verified first');
}
if (!user.verifiedPhoneNumber) {
return ResponseHandler.Unauthorized('Phone number must be verified first');
}
await prisma.user.update({
where: {
id: userId,
},
data: {
enableMFA: true,
},
});
resBody.data = {
status: true,
};
return resBody;
}
@Auth
@apiMethod<IStatusResponse>()
static async disableMFA(): Promise<ApiResponseBody<IStatusResponse>> {
const resBody: ApiResponseBody<IStatusResponse> = (this as any).getResBody();
const userId = this.USER.userId;
const user = await prisma.user.findUnique({
where: { id: userId },
});
if (!user) {
return ResponseHandler.NotFound('User not found');
}
await prisma.user.update({
where: {
id: userId,
},
data: {
enableMFA: false,
},
});
resBody.data = {
status: true,
};
return resBody;
}
private stIatic async handleRole(role: PermissionRole) {
let roleData = await prisma.role.findUnique({
where: {
name: role,
},
});
if (!roleData) {
roleData = await prisma.role.create({ data: { name: role } });
}
return roleData;
}
@apiMethod<PermissionPayload>()
static async setPermission(payload: {
permissions: PermissionPayload;
roleName: PermissionRole;
}): Promise<ApiResponseBody<PermissionPayload>> {
const resBody: ApiResponseBody<PermissionPayload> = (this as any).getResBody();
const role = await this.handleRole(payload.roleName);
const permissionManager = new PermissionManager();
const permissionString = permissionManager.stringify(payload.permissions);
await prisma.permission.upsert({
where:I {
name: permissionString,
roles: { some: { id: role.id } },
},
update: {
name: permissionString,
},
create: {
name: permissionString,
roles: {
connect: {
id: role.id,
},
},
},
});
const permissionPayload = permissionManager.parse(permissionString);
I
resBody.data = permissionPayload;
return resBody;
}
private static async sendEmailMFAVerification(user: User) {
const otpToken = await OTPHandler.generate(user.id);
new MFAEmailMailer(user.email)
.generate({
name: user.name,
OTP: otpToken,
validationPeriod: `${parseStrPeriod(appConfig.mfa.otp.expirationPeriod).value} ${TimeMap[parseStrPeriod(appConfig.mfa.otp.expirationPeriod).unit]}`,
})
.then((instance) => {
instance.sendEmail();
})
.catch((err) => {
logger.error(err);
});
return {
status: true,
};
}
private static async sendPhoneMFAVerification(user: User) {
const otpToken = await OTPHandler.generate(user.id);
if (process.env.STAGE !== 'TEST') {
new MFAMessageMailer(user.phone)
.generate({
name: user.name,
OTP: otpToken,
validationPeriod: `${parseStrPeriod(appConfig.mfa.otp.expirationPeriod).value} ${TimeMap[parseStrPeriod(appConfig.mfa.otp.expirationPeriod).unit]}`,
})
.then((instance) => {
instance.sendSMS();
})
.catch((err) => {
logger.error(err);
});
return {
status: true,
};
} else {
return {
status: true,
otp: otpToken,
};
}
}
private static async sendMFAOtp(
user: User & { otp: Otps | null },
{ method }: TSendMFARequestSchema
) {
if (user.otp && user.otp.expiresAt < new Date()) {
const throttleTimePeriod = parseStrPeriod(appConfig.mfa.otp.throttle);
if (
addTime(throttleTimePeriod.value, throttleTimePeriod.unit, user.otp.createdAt) < new Date()
) {
// Resend
await prisma.otps.delete({
where: {
id: user.otp.id,
},
});
switch (method) {
case 'email':
return await this.sendEmailMFAVerification(user);
case 'phone':
return await this.sendPhoneMFAVerification(user);
}
}
} else {
if (user.otp && user.otp.expiresAt > new Date()) {
await prisma.otps.delete({
where: {
id: user.otp.id,
},
});
}
switch (method) {
case 'email':
return await this.sendEmailMFAVerification(user);
case 'phone':
return await this.sendPhoneMFAVerification(user);
}
}
return {
status: true,
};
}
private static async sendEmailVerification(user: User) {
try {
const token = uuidv4();
await prisma.verifyEmailToken.create({
data: {
token,
userId: user.id,
expiresAt: addTime(1, 'h'),
},
});
new VerifyEmailMailer([user.email])
.generate({
name: user.name,
verificationLink: `${process.env.VERIFY_EMAIL_UI_URL}/${token}`,
})
.then((instance) => {
instance.sendEmail();
});
} catch (err) {
logger.error({ message: 'Send Email Verification Error:', error: err });
}
}
private static async sendConfirmPasswordUpdate(user: User, newPassword: string) {
try {
const token = uuidv4();
const hashedPassword = await bcrypt.hash(newPassword, 10);
await prisma.updatePasswordToken.create({
data: {
token,
newPassword: hashedPassword,
userId: user.id,
expiresAt: addTime(1, 'h'),
},
});
new UpdatePasswordMailer([user.email])
.generate({
name: user.name,
verificationLink: `${process.env.CONFIRM_UPDATE_PASSWORD_EMAIL_UI_URL}/${token}`,
})
.then((instance) => {
instance.sendEmail();
});
} catch (err) {
logger.error({ message: 'Send password update Email Error:', error: err });
}
}
}
|