20 lines
563 B
JavaScript
20 lines
563 B
JavaScript
|
|
/**
|
||
|
|
* Middleware to require a specific role for an endpoint.
|
||
|
|
* @param {string[]} allowedRoles - Array of roles allowed to access the endpoint.
|
||
|
|
* @returns {function} Express middleware function.
|
||
|
|
*/
|
||
|
|
module.exports = (allowedRoles) => {
|
||
|
|
return (req, res, next) => {
|
||
|
|
const userRole = req.user?.role;
|
||
|
|
|
||
|
|
if (!userRole) {
|
||
|
|
return res.status(401).json({ error: 'Authorization required' });
|
||
|
|
}
|
||
|
|
|
||
|
|
if (!allowedRoles.includes(userRole)) {
|
||
|
|
return res.status(403).json({ error: 'Insufficient permissions' });
|
||
|
|
}
|
||
|
|
|
||
|
|
next();
|
||
|
|
};
|
||
|
|
};
|