feat: implement role-based access control and auth routes
Some checks are pending
Docker Test / test (push) Waiting to run
Some checks are pending
Docker Test / test (push) Waiting to run
This commit implements the role-based access control system as outlined in the project documentation. It includes: - A requireRole middleware for protecting routes - Auth routes for registration, login, profile management - Audit logging for sensitive actions - Role management endpoints - Updated app.js to include audit logging middleware
This commit is contained in:
parent
e278ee3da5
commit
37df062f3b
5 changed files with 158 additions and 193 deletions
|
|
@ -1,20 +1,25 @@
|
|||
/**
|
||||
* 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) => {
|
||||
// middleware/requireRole.js
|
||||
const jwt = require('jsonwebtoken');
|
||||
|
||||
function requireRole(allowedRoles) {
|
||||
return (req, res, next) => {
|
||||
const userRole = req.user?.role;
|
||||
const token = req.header('Authorization')?.replace('Bearer ', '');
|
||||
|
||||
if (!userRole) {
|
||||
return res.status(401).json({ error: 'Authorization required' });
|
||||
if (!token) {
|
||||
return res.status(401).json({ error: 'Access denied. No token provided.' });
|
||||
}
|
||||
|
||||
if (!allowedRoles.includes(userRole)) {
|
||||
return res.status(403).json({ error: 'Insufficient permissions' });
|
||||
|
||||
try {
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
if (!allowedRoles.includes(decoded.role)) {
|
||||
return res.status(403).json({ error: 'Access denied. Insufficient permissions.' });
|
||||
}
|
||||
req.user = decoded;
|
||||
next();
|
||||
} catch (error) {
|
||||
res.status(400).json({ error: 'Invalid token.' });
|
||||
}
|
||||
|
||||
next();
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = requireRole;
|
||||
Loading…
Add table
Add a link
Reference in a new issue