2026-03-16 03:06:38 +00:00
|
|
|
/**
|
2026-03-16 07:06:43 +00:00
|
|
|
* Middleware to check if the user has the required role(s)
|
|
|
|
|
* @param {string[]} requiredRoles - Array of required roles
|
|
|
|
|
* @returns {function} Express middleware function
|
2026-03-16 03:06:38 +00:00
|
|
|
*/
|
2026-03-16 07:06:43 +00:00
|
|
|
export const requireRole = (requiredRoles) => {
|
2026-03-16 03:06:38 +00:00
|
|
|
return (req, res, next) => {
|
2026-03-16 07:06:43 +00:00
|
|
|
// Get the user's role from the JWT token (assuming it's in req.user.role)
|
|
|
|
|
const userRole = req.user?.role;
|
|
|
|
|
|
|
|
|
|
// If no user role is found, deny access
|
|
|
|
|
if (!userRole) {
|
|
|
|
|
return res.status(401).json({ error: 'Unauthorized' });
|
2026-03-16 03:06:38 +00:00
|
|
|
}
|
2026-03-16 07:06:43 +00:00
|
|
|
|
|
|
|
|
// Check if the user has at least one of the required roles
|
|
|
|
|
if (requiredRoles.includes(userRole)) {
|
|
|
|
|
next(); // User has the required role, proceed to the next middleware/route
|
|
|
|
|
} else {
|
|
|
|
|
return res.status(403).json({ error: 'Forbidden' });
|
2026-03-16 03:06:38 +00:00
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
};
|