forked from Nova-reward/Nova-Rewards
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauditLogRepository.js
More file actions
235 lines (205 loc) · 5.99 KB
/
Copy pathauditLogRepository.js
File metadata and controls
235 lines (205 loc) · 5.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
const { query } = require('./index');
async function logAudit({
entityType,
entityId = null,
action,
performedBy = null,
actorType = 'system',
merchantId = null,
details = null,
source = null,
beforeState = null,
afterState = null,
ipAddress = null,
userAgent = null,
httpMethod = null,
endpoint = null,
statusCode = null,
durationMs = null
}) {
const result = await query(
`INSERT INTO audit_logs
(entity_type, entity_id, action, performed_by, actor_type, merchant_id, details, source, before_state, after_state, ip_address, user_agent, http_method, endpoint, status_code, duration_ms)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)
RETURNING *`,
[
entityType,
entityId,
action,
performedBy,
actorType,
merchantId,
details ? JSON.stringify(details) : null,
source,
beforeState ? JSON.stringify(beforeState) : null,
afterState ? JSON.stringify(afterState) : null,
ipAddress,
userAgent,
httpMethod,
endpoint,
statusCode,
durationMs
]
);
return result.rows[0];
}
async function getAuditLogs({ entityType, entityId, performedBy, actorType, merchantId, action, startDate, endDate, statusCode, httpMethod, endpoint, ipAddress, page = 1, limit = 20 } = {}) {
const conditions = [];
const params = [];
let i = 1;
if (entityType) {
conditions.push(`entity_type = $${i++}`);
params.push(entityType);
}
if (action) {
conditions.push(`action = $${i++}`);
params.push(action);
}
if (performedBy != null) {
conditions.push(`performed_by = $${i++}`);
params.push(performedBy);
}
if (actorType) {
conditions.push(`actor_type = $${i++}`);
params.push(actorType);
}
if (merchantId != null) {
conditions.push(`merchant_id = $${i++}`);
params.push(merchantId);
}
if (startDate) {
conditions.push(`created_at >= $${i++}`);
params.push(startDate);
}
if (endDate) {
conditions.push(`created_at <= $${i++}`);
params.push(endDate);
}
if (statusCode != null) {
conditions.push(`status_code = $${i++}`);
params.push(statusCode);
}
if (httpMethod) {
conditions.push(`http_method = $${i++}`);
params.push(httpMethod.toUpperCase());
}
if (endpoint) {
conditions.push(`endpoint ILIKE $${i++}`);
params.push(`%${endpoint}%`);
}
if (ipAddress) {
conditions.push(`ip_address = $${i++}`);
params.push(ipAddress);
}
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
const safeLimit = Math.min(Math.max(1, limit), 500);
const offset = (Math.max(1, page) - 1) * safeLimit;
const countResult = await query(
`SELECT COUNT(*) as total FROM audit_logs ${whereClause}`,
params
);
const total = parseInt(countResult.rows[0].total, 10);
const dataResult = await query(
`SELECT
id, entity_type, entity_id, action, performed_by, actor_type, merchant_id,
details, source, ip_address, user_agent, http_method, endpoint,
status_code, duration_ms, created_at
FROM audit_logs ${whereClause}
ORDER BY created_at DESC
LIMIT $${i++} OFFSET $${i++}`,
[...params, safeLimit, offset]
);
return { data: dataResult.rows, total, page: Math.max(1, page), limit: safeLimit };
}
/**
* Exports audit logs as CSV for compliance reporting.
*
* @param {object} filters - Same filters as getAuditLogs
* @returns {Promise<string>} CSV string
*/
async function exportAuditLogsCSV(filters = {}) {
// Fetch all matching records (up to 10,000 for safety)
const result = await getAuditLogs({ ...filters, page: 1, limit: 10000 });
const headers = [
'ID',
'Timestamp',
'Actor Type',
'Performed By',
'Merchant ID',
'Entity Type',
'Entity ID',
'Action',
'HTTP Method',
'Endpoint',
'Status Code',
'Duration (ms)',
'IP Address',
'User Agent',
'Source',
'Details',
];
const rows = result.data.map((log) => [
log.id,
log.created_at,
log.actor_type || '',
log.performed_by || '',
log.merchant_id || '',
log.entity_type || '',
log.entity_id || '',
log.action || '',
log.http_method || '',
log.endpoint || '',
log.status_code || '',
log.duration_ms || '',
log.ip_address || '',
log.user_agent ? `"${log.user_agent.replace(/"/g, '""')}"` : '',
log.source || '',
log.details ? `"${JSON.stringify(log.details).replace(/"/g, '""')}"` : '',
]);
const csv = [headers.join(','), ...rows.map((r) => r.join(','))].join('\n');
return csv;
}
/**
* Gets audit log statistics for dashboard/reporting.
*
* @param {object} filters - Date range and actor filters
* @returns {Promise<object>} Aggregated stats
*/
async function getAuditStats(filters = {}) {
const { startDate, endDate, actorType } = filters;
const conditions = [];
const params = [];
let i = 1;
if (startDate) {
conditions.push(`created_at >= $${i++}`);
params.push(startDate);
}
if (endDate) {
conditions.push(`created_at <= $${i++}`);
params.push(endDate);
}
if (actorType) {
conditions.push(`actor_type = $${i++}`);
params.push(actorType);
}
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
const result = await query(
`SELECT
COUNT(*) AS total_events,
COUNT(DISTINCT performed_by) FILTER (WHERE performed_by IS NOT NULL) AS unique_users,
COUNT(DISTINCT merchant_id) FILTER (WHERE merchant_id IS NOT NULL) AS unique_merchants,
COUNT(*) FILTER (WHERE status_code >= 400) AS error_count,
COUNT(*) FILTER (WHERE status_code >= 200 AND status_code < 300) AS success_count,
AVG(duration_ms) FILTER (WHERE duration_ms IS NOT NULL) AS avg_duration_ms,
MAX(duration_ms) FILTER (WHERE duration_ms IS NOT NULL) AS max_duration_ms
FROM audit_logs ${whereClause}`,
params
);
return result.rows[0];
}
module.exports = {
logAudit,
getAuditLogs,
exportAuditLogsCSV,
getAuditStats,
};