Files
linkedsign/backend/src/modules/audit/audit.repository.js
T

69 lines
2.1 KiB
JavaScript

const db = require('../../config/db');
const fs = require('fs/promises');
const path = require('path');
const saveEvent = async (event) => {
try {
await db.execute(
'INSERT INTO audit_logs (type, user_id, email, ip, user_agent, metadata) VALUES (?, ?, ?, ?, ?, ?)',
[
event.type,
event.userId || null,
event.email || null,
event.ip || null,
event.userAgent || null,
event.metadata ? JSON.stringify(event.metadata) : null,
]
);
} catch (err) {
// Fallback to file log if DB fails
try {
const logsDir = path.resolve(process.cwd(), 'logs');
await fs.mkdir(logsDir, { recursive: true });
await fs.appendFile(
path.resolve(logsDir, 'audit.log'),
`${JSON.stringify({ ...event, _fallback: true })}\n`
);
} catch {
// Silent
}
}
};
const getEvents = async ({ type, userId, limit = 100, offset = 0, types = [] } = {}) => {
let sql = 'SELECT * FROM audit_logs WHERE 1=1';
let countSql = 'SELECT COUNT(*) AS total FROM audit_logs WHERE 1=1';
const params = [];
const countParams = [];
if (type) { sql += ' AND type = ?'; params.push(type); }
if (type) { countSql += ' AND type = ?'; countParams.push(type); }
if (types.length > 0) {
const placeholders = types.map(() => '?').join(', ');
sql += ` AND type IN (${placeholders})`;
countSql += ` AND type IN (${placeholders})`;
params.push(...types);
countParams.push(...types);
}
if (userId) {
sql += ' AND user_id = ?';
countSql += ' AND user_id = ?';
params.push(userId);
countParams.push(userId);
}
sql += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
params.push(limit, offset);
const [rows] = await db.execute(sql, params);
const [countRows] = await db.execute(countSql, countParams);
return {
rows,
total: countRows[0]?.total || 0,
};
};
const deleteEventsByUserId = async (userId) => {
const [result] = await db.execute('DELETE FROM audit_logs WHERE user_id = ?', [userId]);
return result.affectedRows || 0;
};
module.exports = { saveEvent, getEvents, deleteEventsByUserId };