Snai3i-MarketPlace / backend / src / middlewares / auth.middleware.ts
auth.middleware.ts
Raw
import { NextFunction, Response } from 'express';
import { MyRequest, UsersTypes } from '../types/Express';
import { ErrorResponse } from '../utils/Response';
import { HttpCodes } from '../config/Errors';
import { verifyToken } from '../utils/Jwt';
import { authLogs } from '../services/auth/auth.logs';
import { db } from '../settings';
import { AuthServices } from '../services/auth/auth.service';

/**
 * @description  Check if the user is logged in
 * @param {MyRequest<null | UsersTypes>} req - The request object
 * @param {Response} res - The response object
 * @param {NextFunction} next - The next function
 * @returns
 * - {Response} - The response object
 * - {NextFunction} - The next function
 *
 */

export const checkLogs = async (
  req: MyRequest<null | UsersTypes>,
  res: Response,
  next: NextFunction
) => {
  const token = req.cookies.token;
  req.user = null;
  if (token) {
    try {
      const payload = verifyToken(token);
      if (!payload || !payload.user_id) {
        res.clearCookie('token');
        return ErrorResponse(
          res,
          HttpCodes.Unauthorized.code,
          authLogs.ERROR_WHILE_CHECKING_CREDENTIALS.message,
          authLogs.ERROR_WHILE_CHECKING_CREDENTIALS
        );
      }
      const { user_id } = payload;

      const sqlquery = 'SELECT * FROM users WHERE user_id = ?';
      let [[user]] = await db.query<UserI[]>(sqlquery, [user_id]);

      if (!user) {
        res.clearCookie('token');
        return ErrorResponse(
          res,
          HttpCodes.Unauthorized.code,
          authLogs.ERROR_WHILE_CHECKING_CREDENTIALS.message,
          authLogs.ERROR_WHILE_CHECKING_CREDENTIALS
        );
      }

      if (user.isActive === 0) {
        res.clearCookie('token');
        return ErrorResponse(
          res,
          HttpCodes.Unauthorized.code,
          authLogs.USER_IS_NOT_ACTIVE.message,
          authLogs.USER_IS_NOT_ACTIVE
        );
      }

      if (user.role !== 'admin' && user.role !== 'super_admin') {
        const additionalInfo = await AuthServices.getAdditionalInfo(
          user.role,
          user.user_id
        );
        user = { ...user, ...additionalInfo };
        if (additionalInfo instanceof ErrorResponse) {
          res.clearCookie('token');
          return ErrorResponse(
            res,
            HttpCodes.Unauthorized.code,
            'Error while checking additional info for user',
            additionalInfo.err
          );
        }
      }

      req.user = user;
    } catch (e) {
      res.clearCookie('token');
      return ErrorResponse(
        res,
        HttpCodes.InternalServerError.code,
        authLogs.ERROR_WHILE_CHECKING_CREDENTIALS.message,
        e
      );
    }
  } else {
    return ErrorResponse(
      res,
      HttpCodes.Unauthorized.code,
      authLogs.ERROR_SESSION_CREDENTIALS.message
    );
  }
  return next();
};

/**
 * @description  Check if the user is logged in
 * @param {MyRequest<UserD>} req - The request object
 * @param {Response} res - The response object
 * @param {NextFunction} next - The next function
 * @returns
 * - {Response} - The response object
 * - {NextFunction} - The next function
 *
 */
export const isLoggedIn = (
  req: MyRequest<UsersTypes>,
  res: Response,
  next: NextFunction
) => {
  if (req.user) {
    return next();
  }
  ErrorResponse(
    res,
    HttpCodes.Unauthorized.code,
    authLogs.USER_ISN_T_LOGGED.message,
    authLogs.USER_ISN_T_LOGGED
  );
};

/**
 * @description  Check if the user is an admin
 * @param {MyRequest<UserD>} req - The request object
 * @param {Response} res - The response object
 * @param {NextFunction} next - The next function
 * @returns
 * - {Response} - The response object
 * - {NextFunction} - The next function
 *
 */
export const isAdmin = (
  req: MyRequest<UsersTypes>,
  res: Response,
  next: NextFunction
) => {
  if (
    req.user &&
    (req.user.role === 'admin' ||
      req.user.role === 'super_admin' ||
      req.user.role === 'inst_admin')
  ) {
    return next();
  }
  return ErrorResponse(
    res,
    HttpCodes.Unauthorized.code,
    authLogs.USER_ISN_T_ADMIN.message,
    authLogs.USER_ISN_T_ADMIN
  );
};

/**
 * @description  Check if the user is an super admin
 * @param {MyRequest<UserD>} req - The request object
 * @param {Response} res - The response object
 * @param {NextFunction} next - The next function
 * @returns
 * - {Response} - The response object
 * - {NextFunction} - The next function
 *
 */
export const isSuperAdmin = (
  req: MyRequest<UsersTypes>,
  res: Response,
  next: NextFunction
) => {
  if (req.user && req.user.role === 'super_admin') {
    return next();
  }
  return ErrorResponse(
    res,
    HttpCodes.Unauthorized.code,
    authLogs.USER_ISN_T_SUPER_ADMIN.message,
    authLogs.USER_ISN_T_SUPER_ADMIN
  );
};

/**
 * @description  Check if the user is an instructional designer
 * @param {MyRequest<UserD>} req - The request object
 * @param {Response} res - The response object
 * @param {NextFunction} next - The next function
 * @returns
 * - {Response} - The response object
 * - {NextFunction} - The next function
 *
 */
export const isInstDesign = (
  req: MyRequest<UsersTypes>,
  res: Response,
  next: NextFunction
) => {
  if (
    req.user &&
    (req.user.role === 'inst_designer' ||
      req.user.role === 'admin' ||
      req.user.role === 'super_admin')
  ) {
    return next();
  }
  return ErrorResponse(
    res,
    HttpCodes.Unauthorized.code,
    authLogs.USER_ISN_T_INST_DESIGNER.message,
    authLogs.USER_ISN_T_INST_DESIGNER
  );
};

/**
 * @description  Check if the user is a teacher
 * @param {MyRequest<UserD>} req - The request object
 * @param {Response} res - The response object
 * @param {NextFunction} next - The next function
 * @returns
 * - {Response} - The response object
 * - {NextFunction} - The next function
 *
 */

export const isTeacher = (
  req: MyRequest<UsersTypes>,
  res: Response,
  next: NextFunction
) => {
  if (
    req.user &&
    (req.user.role === 'teacher' ||
      req.user.role === 'admin' ||
      req.user.role === 'super_admin')
  ) {
    return next();
  }
  return ErrorResponse(
    res,
    HttpCodes.Unauthorized.code,
    authLogs.USER_ISN_T_TEACHER.message,
    authLogs.USER_ISN_T_TEACHER
  );
};

/**
 * @description  Check if the user is a school
 * @param {MyRequest<UserD>} req - The request object
 * @param {Response} res - The response object
 * @param {NextFunction} next - The next function
 * @returns
 * - {Response} - The response object
 * - {NextFunction} - The next function
 *
 */
export const isSchool = (
  req: MyRequest<UsersTypes>,
  res: Response,
  next: NextFunction
) => {
  if (
    req.user &&
    (req.user.role === 'school' ||
      req.user.role === 'admin' ||
      req.user.role === 'super_admin')
  ) {
    return next();
  }
  return ErrorResponse(
    res,
    HttpCodes.Unauthorized.code,
    authLogs.USER_ISN_T_SCHOOL.message,
    authLogs.USER_ISN_T_SCHOOL
  );
};