spurrin-backend/src/middlewares/authorizeMiddleware.js
2025-06-09 11:11:52 +05:30

32 lines
1.0 KiB
JavaScript

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