const { ForbiddenError } = require('../utils/errors'); const logger = require('../utils/logger'); /** * Middleware to authorize users based on their roles * @param {string[]} allowedRoles - Array of roles that are allowed to access the route * @returns {Function} Express middleware function */ const authorize = (allowedRoles) => { return (req, res, next) => { try { // Check if user exists in request (set by authenticate middleware) if (!req.user) { throw new ForbiddenError('User not authenticated'); } // Check if user has required role if (!allowedRoles.includes(req.user.role)) { logger.warn(`Unauthorized access attempt by user ${req.user.id} with role ${req.user.role}`); throw new ForbiddenError('You do not have permission to perform this action'); } next(); } catch (error) { next(error); } }; }; module.exports = { authorize };