init: init project
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import { configs } from "../configs";
|
||||
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;
|
||||
Reference in New Issue
Block a user