|
| 1 | +import { db } from './db'; |
| 2 | + |
| 3 | +interface AuditLog { |
| 4 | + id: number; |
| 5 | + discord_id: string | null; |
| 6 | + action: string; |
| 7 | + details: string | null; |
| 8 | + created_at: string; |
| 9 | +} |
| 10 | + |
| 11 | +class AuditManager { |
| 12 | + /** |
| 13 | + * Log an action to the audit log |
| 14 | + */ |
| 15 | + async logAction(discordId: string | null, action: string, details?: any): Promise<void> { |
| 16 | + const detailsStr = details ? JSON.stringify(details) : null; |
| 17 | + await db.run( |
| 18 | + `INSERT INTO audit_log (discord_id, action, details) |
| 19 | + VALUES (?, ?, ?)`, |
| 20 | + [discordId, action, detailsStr] |
| 21 | + ); |
| 22 | + } |
| 23 | + |
| 24 | + /** |
| 25 | + * Get audit log entries for a specific user |
| 26 | + */ |
| 27 | + async getUserAuditLog(discordId: string, limit: number = 50): Promise<AuditLog[]> { |
| 28 | + return db.all<AuditLog>( |
| 29 | + `SELECT id, discord_id, action, details, created_at |
| 30 | + FROM audit_log |
| 31 | + WHERE discord_id = ? |
| 32 | + ORDER BY created_at DESC |
| 33 | + LIMIT ?`, |
| 34 | + [discordId, limit] |
| 35 | + ); |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * Get all audit log entries (admin function) |
| 40 | + */ |
| 41 | + async getAllAuditLog(limit: number = 100): Promise<AuditLog[]> { |
| 42 | + return db.all<AuditLog>( |
| 43 | + `SELECT id, discord_id, action, details, created_at |
| 44 | + FROM audit_log |
| 45 | + ORDER BY created_at DESC |
| 46 | + LIMIT ?`, |
| 47 | + [limit] |
| 48 | + ); |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * Get audit log entries since a specific timestamp |
| 53 | + */ |
| 54 | + async getAuditLogSince(timestamp: string, limit: number = 100): Promise<AuditLog[]> { |
| 55 | + return db.all<AuditLog>( |
| 56 | + `SELECT id, discord_id, action, details, created_at |
| 57 | + FROM audit_log |
| 58 | + WHERE created_at >= ? |
| 59 | + ORDER BY created_at DESC |
| 60 | + LIMIT ?`, |
| 61 | + [timestamp, limit] |
| 62 | + ); |
| 63 | + } |
| 64 | + |
| 65 | + /** |
| 66 | + * Get audit log entries for a specific action |
| 67 | + */ |
| 68 | + async getAuditLogByAction(action: string, limit: number = 50): Promise<AuditLog[]> { |
| 69 | + return db.all<AuditLog>( |
| 70 | + `SELECT id, discord_id, action, details, created_at |
| 71 | + FROM audit_log |
| 72 | + WHERE action = ? |
| 73 | + ORDER BY created_at DESC |
| 74 | + LIMIT ?`, |
| 75 | + [action, limit] |
| 76 | + ); |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +export const auditManager = new AuditManager(); |
0 commit comments