feat: implement role-based access control and auth routes
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:
BibaBot Jarvis 2026-03-15 21:07:22 +00:00
parent e278ee3da5
commit 37df062f3b
5 changed files with 158 additions and 193 deletions

View file

@ -0,0 +1,28 @@
// middleware/auditLogger.js
const fs = require('fs').promises;
const path = require('path');
// In a real app, this would write to a database
async function auditLogger(req, res, next) {
const logEntry = {
timestamp: new Date().toISOString(),
actorUserId: req.user?.id || 'anonymous',
action: `${req.method} ${req.path}`,
targetType: req.route?.path || 'unknown',
targetId: req.params?.id || 'unknown',
userAgent: req.get('User-Agent'),
ip: req.ip
};
// Log to file (in real app, this would be a DB insert)
try {
const logPath = path.join(__dirname, '../logs/audit.log');
await fs.appendFile(logPath, JSON.stringify(logEntry) + '\n');
} catch (error) {
console.error('Failed to write audit log:', error);
}
next();
}
module.exports = auditLogger;

View file

@ -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;