const AuditLog = require('../models/AuditLogModel') const SENSITIVE_KEYS = new Set(['password', 'new_password', 'token', 'otp']) const WRITE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']) function sanitizeBody(body) { if (!body || typeof body !== 'object') return null const clone = {} for (const [key, value] of Object.entries(body)) { clone[key] = SENSITIVE_KEYS.has(key) ? '[hidden]' : value } return clone } // باید بعد از adminAuth بیاد (به req.admin نیاز داره). فقط متدهای نوشتاری رو ثبت // می‌کنه — GET یعنی فقط دیدن، نه یه «کار انجام‌شده» که نیاز به تاریخچه داشته باشه module.exports = function auditLogger(req, res, next) { if (!WRITE_METHODS.has(req.method)) return next() res.on('finish', () => { if (!req.admin) return AuditLog.create({ adminId: req.admin._id, adminUserName: req.admin.user_name, method: req.method, path: req.originalUrl, statusCode: res.statusCode, body: sanitizeBody(req.body) }).catch((err) => { console.error('[auditLogger] failed to write audit log:', err.message) }) }) next() }