feat: implement comprehensive audit logging system

This commit is contained in:
nguyenvanbao
2026-02-10 16:42:35 +07:00
parent d440a04618
commit 970fcbac7d
28 changed files with 4783 additions and 2221 deletions

40
audit/diffObject.js Normal file
View File

@@ -0,0 +1,40 @@
function diffObject(before = {}, after = {}, parentPath = "") {
const changes = [];
const allKeys = new Set([
...Object.keys(before || {}),
...Object.keys(after || {}),
]);
for (const key of allKeys) {
const beforeValue = before?.[key];
const afterValue = after?.[key];
const currentPath = parentPath ? `${parentPath}.${key}` : key;
// Nếu cả hai đều là object (không phải array)
if (
typeof beforeValue === "object" &&
typeof afterValue === "object" &&
beforeValue !== null &&
afterValue !== null &&
!Array.isArray(beforeValue) &&
!Array.isArray(afterValue)
) {
changes.push(...diffObject(beforeValue, afterValue, currentPath));
continue;
}
// So sánh primitive hoặc array
if (JSON.stringify(beforeValue) !== JSON.stringify(afterValue)) {
changes.push({
field: currentPath,
before: beforeValue,
after: afterValue,
});
}
}
return changes;
}
module.exports = diffObject;

25
audit/writeAuditLog.js Normal file
View File

@@ -0,0 +1,25 @@
const AuditLog = require("../models/auditLog");
const RequestMeta = require("../utils/requestMeta");
async function writeAuditLog({
model,
documentId,
action,
before,
after,
changes = [],
req,
}) {
await AuditLog.create({
model,
documentId,
action,
before,
after,
changes,
ipAddress: RequestMeta.getClientIp(req),
userAgent: RequestMeta.getUserAgent(req),
performedBy: req.session?.user?.id || req.user?.id || null,
});
}
module.exports = writeAuditLog;