forked from UKSOURCE/cms.hailearning.edu.vn
feat: implement comprehensive audit logging system
This commit is contained in:
40
audit/diffObject.js
Normal file
40
audit/diffObject.js
Normal 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
25
audit/writeAuditLog.js
Normal 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;
|
||||
Reference in New Issue
Block a user