28 lines
805 B
JavaScript
28 lines
805 B
JavaScript
|
|
// 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;
|