feat: Add role middleware and update permissions documentation
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
30bd7f0214
commit
1f3e567d3a
1 changed files with 12 additions and 9 deletions
|
|
@ -1,20 +1,23 @@
|
|||
/**
|
||||
* Middleware to check if the user has the required role(s)
|
||||
* @param {string[]} allowedRoles - Array of roles allowed to access the endpoint
|
||||
* @param {string[]} requiredRoles - Array of required roles
|
||||
* @returns {function} Express middleware function
|
||||
*/
|
||||
export const requireRole = (allowedRoles) => {
|
||||
export 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: Missing role claim' });
|
||||
return res.status(401).json({ error: 'Unauthorized' });
|
||||
}
|
||||
|
||||
if (!allowedRoles.includes(userRole)) {
|
||||
return res.status(403).json({ error: 'Forbidden: Insufficient permissions' });
|
||||
|
||||
// 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' });
|
||||
}
|
||||
|
||||
next();
|
||||
};
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue