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()); } } }