24 lines
810 B
JavaScript
24 lines
810 B
JavaScript
|
|
import { configs } from "../configs/index.js";
|
||
|
|
import { AppError } from "../utils/app_error.js";
|
||
|
|
import { jwtHelpers } from "../utils/JWT.js";
|
||
|
|
const auth = (...roles) => {
|
||
|
|
return async (req, res, next) => {
|
||
|
|
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);
|
||
|
|
if (!roles.length || !roles.includes(verifiedUser.role)) {
|
||
|
|
throw new AppError("You are not authorize!!", 401);
|
||
|
|
}
|
||
|
|
req.user = verifiedUser;
|
||
|
|
next();
|
||
|
|
}
|
||
|
|
catch (err) {
|
||
|
|
next(err);
|
||
|
|
}
|
||
|
|
};
|
||
|
|
};
|
||
|
|
export default auth;
|