feat: Implement role-based access control middleware and tests
Some checks are pending
Docker Test / test (push) Waiting to run

This commit is contained in:
BibaBot 2026-03-17 10:09:15 +00:00
parent 95a2d85aa3
commit 963d8c3aa5
3 changed files with 31 additions and 81 deletions

View file

@ -1,23 +1,26 @@
/**
* Middleware to check if the user has the required role(s)
* @param {string[]} requiredRoles - Array of required roles
* @returns {function} Express middleware function
*/
export const requireRole = (requiredRoles) => {
// Role-based access control middleware
const requireRole = (requiredRoles) => {
return (req, res, next) => {
// 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' });
// Check if user is authenticated
if (!req.user) {
return res.status(401).json({
error: 'Authentication required'
});
}
// Check if the user has at least one of the required roles
// Check if user has the required role
const userRole = req.user.role;
if (requiredRoles.includes(userRole)) {
next(); // User has the required role, proceed to the next middleware/route
// User has the required role, allow access
next();
} else {
return res.status(403).json({ error: 'Forbidden' });
// User does not have the required role, deny access
return res.status(403).json({
error: 'Insufficient permissions'
});
}
};
};
};
module.exports = { requireRole };