All files / src/decorators auth.decorator.ts

86.66% Statements 39/45
86.11% Branches 31/36
92.85% Functions 13/14
92.5% Lines 37/40

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  7x 17x 13x 17x   30x 13x     7x 7x   7x 7x 7x 7x 7x 7x 7x 7x 7x     11x 11x             11x 2x   9x       2x 2x 2x 2x             2x 2x       2x               7x  
import { AuthFacade } from '@/facades/auth.facade';
import { ConfirmDeleteMailer } from '@/messager/confirm-deleting.mailer';
import prisma from '@/services/prisma.service';
import { addTime } from '@/utils/helpers';
import { logger } from '@/utils/winston';
import { $Enums, User } from '@prisma/client';
import { v4 as uuidv4 } from 'uuid';
 
export class AuthClass {
  static USER: IAuthUser;
  protected static async isValidUser(userId: string, type: $Enums.UserType) {
    const user = await prisma.user.findUnique({
      where: { id: userId },
      include: {
        patient: true,
        doctor: true,
      },
    });
 
    if (user?.patient || user?.doctor) {
      return false;
    }
 
    return user?.userType === type;
  }
 
  protected static async sendConfirmDeletionToken(user: User) {
    try {
      const token = uuidv4();
 
      await prisma.confirmDeletionToken.create({
        data: {
          token,
          userId: user.id,
          expiresAt: addTime(1, 'h'),
        },
      });
      const _mailer = new ConfirmDeleteMailer([user.email]);
      await _mailer.generate({
        name: user.name,
        verificationLink: `${process.env.DELETE_PROFILE_UI_URL}/${token}`,
      });
      await _mailer.sendEmail();
    } catch (err) {
      logger.error({ message: 'Send Email Verification Error:', error: err });
    }
  }
}
 
export function Auth(_: any, __: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;
 
  descriptor.value = function (this: { USER: IAuthUser }, ...args: any[]) {
    const user = AuthFacade.get();
    if (!user) {
      throw new Error('User not found');
    }
    this.USER = user;
    return originalMethod.apply(this, args);
  };
 
  return descriptor;
}