2026-04-02 21:27:09 +06:00
|
|
|
import { NextFunction, Request, Response } from "express";
|
2026-04-13 00:13:52 +06:00
|
|
|
import { configs } from "../configs";
|
2026-04-02 21:27:09 +06:00
|
|
|
import { AppError } from "../utils/app_error";
|
|
|
|
|
import { jwtHelpers, JwtPayloadType } from "../utils/JWT";
|
|
|
|
|
|
|
|
|
|
type Role = "ADMIN" | "USER";
|
|
|
|
|
|
|
|
|
|
const auth = (...roles: Role[]) => {
|
|
|
|
|
return async (req: Request, res: Response, next: NextFunction) => {
|
|
|
|
|
try {
|
|
|
|
|
const token = req.headers.authorization || req.cookies.access_token;
|
|
|
|
|
if (!token) {
|
|
|
|
|
throw new AppError("You are not authorize!!", 401);
|
|
|
|
|
}
|
|
|
|
|
const verifiedUser = jwtHelpers.verifyToken(
|
|
|
|
|
token,
|
|
|
|
|
configs.jwt.access_token as string,
|
|
|
|
|
);
|
|
|
|
|
if (!roles.length || !roles.includes(verifiedUser.role)) {
|
|
|
|
|
throw new AppError("You are not authorize!!", 401);
|
|
|
|
|
}
|
|
|
|
|
req.user = verifiedUser as JwtPayloadType;
|
|
|
|
|
next();
|
|
|
|
|
} catch (err) {
|
|
|
|
|
next(err);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export default auth;
|