Files
vitfit-r2/V2/app/modules/audit/routes.js
T
2026-06-13 08:03:45 -04:00

61 lines
2.5 KiB
JavaScript

'use strict';
const express = require('express');
const { Op } = require('sequelize');
const { models } = require('../../core/db');
const { authenticateToken, authenticateRole } = require('../../core/auth');
const { collection } = require('../../core/respond');
const { DateTime } = require('luxon');
const router = express.Router();
router.prefix = 'audit-logs';
const OWNERS = ['Owner', 'SystemAdmin'];
router.get('/', authenticateToken, authenticateRole(OWNERS), async (req, res, next) => {
try {
const { action, userId, entityType, from, to, page = 1, limit = 50 } = req.query;
const where = { organizationId: req.user.organizationId };
if (action) where.action = action;
if (userId) where.userId = parseInt(userId, 10);
if (entityType) where.entityType = entityType;
if (from) where.createdAt = { [Op.gte]: new Date(from) };
if (to) where.createdAt = { ...where.createdAt, [Op.lte]: new Date(to) };
const offset = (parseInt(page, 10) - 1) * parseInt(limit, 10);
const { rows, count } = await models.AuditLog.findAndCountAll({
where, limit: +limit, offset, order: [['createdAt', 'DESC']],
});
collection(res, rows, count, +page, +limit);
} catch (err) { next(err); }
});
router.get('/export', authenticateToken, authenticateRole(OWNERS), async (req, res, next) => {
try {
const { action, userId, entityType, from, to } = req.query;
const where = { organizationId: req.user.organizationId };
if (action) where.action = action;
if (userId) where.userId = parseInt(userId, 10);
if (entityType) where.entityType = entityType;
if (from) where.createdAt = { [Op.gte]: new Date(from) };
if (to) where.createdAt = { ...where.createdAt, [Op.lte]: new Date(to) };
const rows = await models.AuditLog.findAll({ where, order: [['createdAt', 'DESC']] });
const date = DateTime.now().toISODate();
res.setHeader('Content-Type', 'text/csv');
res.setHeader('Content-Disposition', `attachment; filename="audit-log-${date}.csv"`);
const header = 'id,createdAt,userId,userRole,action,entityType,entityId,ipAddress,details\n';
res.write(header);
for (const row of rows) {
const details = JSON.stringify(row.details || {}).replace(/"/g, '""');
res.write(`${row.id},"${row.createdAt}",${row.userId},"${row.userRole}","${row.action}","${row.entityType}",${row.entityId},"${row.ipAddress}","${details}"\n`);
}
res.end();
} catch (err) { next(err); }
});
module.exports = router;