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 { UserModel } from "../models/user.model";
/**
* @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._id)
return ErrorResponse(
res,
HttpCodes.Unauthorized.code,
authLogs.ERROR_WHILE_CHECKING_CREDENTIALS.message,
authLogs.ERROR_WHILE_CHECKING_CREDENTIALS
);
const { _id } = payload;
const user = await UserModel.findOne({ _id });
if (!user) {
return ErrorResponse(
res,
HttpCodes.Unauthorized.code,
authLogs.ERROR_WHILE_CHECKING_CREDENTIALS.message,
authLogs.ERROR_WHILE_CHECKING_CREDENTIALS
);
}
req.user = user;
} catch (e) {
res.clearCookie("token");
return ErrorResponse(
res,
HttpCodes.InternalServerError.code,
authLogs.ERROR_WHILE_CHECKING_CREDENTIALS.message,
e
);
}
}
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
);
};
export const isAdmin = (
req: MyRequest<UsersTypes>,
res: Response,
next: NextFunction
) => {
if (req.user?.role === "admin") {
return next();
}
ErrorResponse(
res,
HttpCodes.Unauthorized.code,
authLogs.USER_ISN_T_ADMIN.message,
authLogs.USER_ISN_T_ADMIN
);
}