You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

34 lines
1023 B
JavaScript

import jwt from 'jsonwebtoken';
import ApiError from '../controllers/ErrorController.js';
import config from "config";
export default function(roles) {
return function(req, res, next) {
if(req.method === 'OPTIONS') {
next();
}
try {
const authHeader = req.headers.authorization;
if(!authHeader) {
return next(ApiError.UnauthorizedError());
}
const accessToken = authHeader.split(' ')[1];
if(!accessToken) {
return next(ApiError.UnauthorizedError());
}
const decodedData = TokenService.validateAccessToken(accessToken);
if(!decodedData) {
return next(ApiError.UnauthorizedError());
}
if(!roles.includes(decodedData.role)) {
return next(ApiError.ForbiddenError());
}
next();
} catch (e) {
return next(ApiError.UnauthorizedError());
}
}
}