All files / src/middlewares requireVerifiedEmail.middleware.ts

71.42% Statements 25/35
83.33% Branches 20/24
90% Functions 9/10
76.66% Lines 23/30

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  7x 2x 2x 2x   4x 2x     7x 7x   7x 7x 7x 7x 7x   2x 2x 2x 2x         2x         2x         2x 1x     1x 1x
import { Request, Response, NextFunction } from 'express';
import { ApiResponseBody, ResponseHandler } from '@/utils/responseHandler';
import { AuthFacade } from '@/facades/auth.facade';
import prisma from '@/services/prisma.service';

export async function requireVerifiedEmail(_: Request, res: Response, next: NextFunction) {
  try {
    const userBody = AuthFacade.get();
 
    if (!userBody) {
      const resBody = ResponseHandler.Unauthorized('Unauthenticated');
      res.status(resBody.error!.code).json(resBody);
    } else {
      const user = await prisma.user.findUnique({
        where: {
          id: userBody.userId,
        },
      });
 
      if (!user) {
        const resBody = ResponseHandler.Forbidden('Unauthorized');
        res.status(resBody.error!.code).json(resBody);
      } elseI {
        if (user.verifiedEmail) {
          next();
        } else {
          const resBody = ResponseHandler.Forbidden('Your email must be verified!');
          res.status(resBody.error!.code).json(resBody);
        }
      }
    }
  } catch (error: any) {
    const resBodIy: ApiResponseBody = {
      error: {
        code: 505,
        message: String(error),
      },
    };
 
    res.status(resBody.error!.code).json(resBody);
  }
}