feat: Add role-based access control middleware and tests
Some checks are pending
Docker Test / test (push) Waiting to run
Some checks are pending
Docker Test / test (push) Waiting to run
This commit is contained in:
parent
901bcf454c
commit
eb45e4474d
6 changed files with 58 additions and 165 deletions
26
backend/middleware/role.middleware.cjs
Normal file
26
backend/middleware/role.middleware.cjs
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
// Role-based access control middleware
|
||||
const requireRole = (requiredRoles) => {
|
||||
return (req, res, next) => {
|
||||
// Check if user is authenticated
|
||||
if (!req.user) {
|
||||
return res.status(401).json({
|
||||
error: 'Authentication required'
|
||||
});
|
||||
}
|
||||
|
||||
// Check if user has the required role
|
||||
const userRole = req.user.role;
|
||||
|
||||
if (!userRole || !requiredRoles.includes(userRole)) {
|
||||
// User does not have the required role, deny access
|
||||
return res.status(403).json({
|
||||
error: 'Insufficient permissions'
|
||||
});
|
||||
}
|
||||
|
||||
// User has the required role, allow access
|
||||
next();
|
||||
};
|
||||
};
|
||||
|
||||
module.exports = { requireRole };
|
||||
|
|
@ -11,16 +11,16 @@ const requireRole = (requiredRoles) => {
|
|||
// Check if user has the required role
|
||||
const userRole = req.user.role;
|
||||
|
||||
if (requiredRoles.includes(userRole)) {
|
||||
// User has the required role, allow access
|
||||
next();
|
||||
} else {
|
||||
if (!userRole || !requiredRoles.includes(userRole)) {
|
||||
// User does not have the required role, deny access
|
||||
return res.status(403).json({
|
||||
error: 'Insufficient permissions'
|
||||
});
|
||||
}
|
||||
|
||||
// User has the required role, allow access
|
||||
next();
|
||||
};
|
||||
};
|
||||
|
||||
export { requireRole };
|
||||
module.exports = { requireRole };
|
||||
Loading…
Add table
Add a link
Reference in a new issue