Snai3i-LandingPage-FormBuilder / backend / src / middlewares / authMiddleware.ts
authMiddleware.ts
Raw
import { Response, NextFunction } from 'express';
import { RequestWithUser } from '../types/Express';
import jwt from 'jsonwebtoken';
import { JwtSecret } from '../config/env';
import { ErrorResponse } from '../utils/response';
import { HttpCodes } from '../config/errors';
import userModel from '../models/userModel';

export const protect = async (
  req: RequestWithUser,
  res: Response,
  next: NextFunction
) => {
  const token = req.cookies.token;
  req.user = null;
  if (token) {
    try {
      const payload = jwt.verify(token, JwtSecret) as MyPayload;
      if (!payload || !payload._id)
        return ErrorResponse(
          res,
          HttpCodes.Unauthorized.code,
          "Couldn't create a correct session - Invalid token."
        );
      const { _id } = payload;

      const user = await userModel.findOne({ _id });
      if (!user) {
        return ErrorResponse(
          res,
          HttpCodes.Unauthorized.code,
          "Couldn't create a correct session.- Invalid token."
        );
      }
      req.user = user;
    } catch (e) {
      res.cookie('token', '', {
        sameSite: 'none',
        httpOnly: true,
        expires: new Date(0),
      });

      return ErrorResponse(
        res,
        HttpCodes.InternalServerError.code,
        "Couldn't create a correct session."
      );
    }
    return next();
  } else {
    ErrorResponse(
      res,
      HttpCodes.Unauthorized.code,
      "You aren't logged in to do this action."
    );
  }
};

export const checkSuperAdmin = async (
  req: RequestWithUser,
  res: Response,
  next: NextFunction
) => {
  const userRole = req.user?.role;
  if (userRole !== 'superAdmin') {
    return ErrorResponse(
      res,
      HttpCodes.Forbidden.code,
      "You don't have permission to do this action."
    );
  }
  next();
};