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 is contained in:
parent
91eb0828e3
commit
7c9862a08a
3 changed files with 344 additions and 45 deletions
|
|
@ -1,28 +1,33 @@
|
|||
// middleware/auditLogger.js
|
||||
const fs = require('fs').promises;
|
||||
const path = require('path');
|
||||
const db = require('../db');
|
||||
|
||||
// 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
|
||||
/**
|
||||
* Middleware zur Protokollierung sensibler Aktionen
|
||||
* @param {string} action - Name der Aktion (z.B. 'USER_SUSPEND')
|
||||
* @param {string} targetType - Typ des Zielobjekts (z.B. 'user')
|
||||
* @returns {function} Express-Middleware-Funktion
|
||||
*/
|
||||
function auditLogger(action, targetType) {
|
||||
return async (req, res, next) => {
|
||||
try {
|
||||
const timestamp = new Date().toISOString();
|
||||
const actorUserId = req.user?.id || null;
|
||||
const targetId = req.params.id || req.body.id || null;
|
||||
const reason = req.body.reason || null;
|
||||
|
||||
// Audit-Eintrag in die Datenbank schreiben
|
||||
await db.run(
|
||||
'INSERT INTO audit_log (timestamp, actor_user_id, action, target_type, target_id, reason) VALUES (?, ?, ?, ?, ?, ?)',
|
||||
[timestamp, actorUserId, action, targetType, targetId, reason]
|
||||
);
|
||||
|
||||
next();
|
||||
} catch (err) {
|
||||
console.error('Audit logging failed:', err);
|
||||
// Fehler bei Audit-Logging sollte nicht den Request blockieren
|
||||
next();
|
||||
}
|
||||
};
|
||||
|
||||
// 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;
|
||||
|
|
@ -1,18 +1,30 @@
|
|||
// middleware/requireRole.js
|
||||
const requireRole = (allowedRoles) => {
|
||||
const jwt = require('jsonwebtoken');
|
||||
|
||||
/**
|
||||
* Middleware zur Prüfung der Benutzerrolle
|
||||
* @param {string[]} allowedRoles - Erlaubte Rollen
|
||||
* @returns {function} Express-Middleware-Funktion
|
||||
*/
|
||||
function requireRole(allowedRoles) {
|
||||
return (req, res, next) => {
|
||||
const userRole = req.user?.role;
|
||||
|
||||
if (!userRole) {
|
||||
return res.status(401).json({ error: 'Authorization required' });
|
||||
const authHeader = req.headers.authorization;
|
||||
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
||||
return res.status(401).json({ error: 'Authorization header missing or invalid' });
|
||||
}
|
||||
|
||||
if (!allowedRoles.includes(userRole)) {
|
||||
return res.status(403).json({ error: 'Insufficient permissions' });
|
||||
|
||||
const token = authHeader.substring(7); // "Bearer " entfernen
|
||||
try {
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
if (!decoded.role || !allowedRoles.includes(decoded.role)) {
|
||||
return res.status(403).json({ error: 'Insufficient permissions' });
|
||||
}
|
||||
req.user = decoded; // Nutzerdaten an die Request-Objekt anhängen
|
||||
next();
|
||||
} catch (err) {
|
||||
return res.status(401).json({ error: 'Invalid token' });
|
||||
}
|
||||
|
||||
next();
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = requireRole;
|
||||
Loading…
Add table
Add a link
Reference in a new issue