# Audit Log Feature Centralized audit logging system for tracking all user and system actions across MotoVaultPro. ## Architecture ``` Frontend +--------------+ +-------------------+ | AdminLogsPage| | AdminLogsMobile | | (desktop) | | Screen (mobile) | +------+-------+ +--------+----------+ | | +-------------------+ | | useAuditLogs hook v adminApi.unifiedAuditLogs | | HTTP v GET /api/admin/audit-logs?search=X&category=Y&... GET /api/admin/audit-logs/export | +--------v--------+ | AuditLogController | +--------+--------+ | +--------v--------+ | AuditLogService |<----- Other services call | log(category,...)| auditLogService.info() +--------+--------+ | +--------v--------+ | AuditLogRepository | +--------+--------+ v +-------------+ | audit_logs | (PostgreSQL) +-------------+ ``` ## Data Flow ``` Feature Service (vehicles, auth, etc.) | | auditLogService.info(category, userId, action, resourceType?, resourceId?, details?) v AuditLogService | | INSERT INTO audit_logs v PostgreSQL audit_logs table | | GET /api/admin/audit-logs (with filters) v AdminLogsPage/Mobile displays filtered, paginated results ``` ## Database Schema ```sql CREATE TABLE audit_logs ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), category VARCHAR(20) NOT NULL CHECK (category IN ('auth', 'vehicle', 'user', 'system', 'admin')), severity VARCHAR(10) NOT NULL CHECK (severity IN ('info', 'warning', 'error')), user_id VARCHAR(255), -- NULL for system-initiated actions action VARCHAR(500) NOT NULL, resource_type VARCHAR(100), resource_id VARCHAR(255), details JSONB, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); ``` ## Indexes - `idx_audit_logs_category_created` - B-tree for category filtering - `idx_audit_logs_severity_created` - B-tree for severity filtering - `idx_audit_logs_user_created` - B-tree for user filtering - `idx_audit_logs_created` - B-tree for date ordering - `idx_audit_logs_action_gin` - GIN trigram for text search ## API Endpoints ### GET /api/admin/audit-logs Returns paginated audit logs with optional filters. **Query Parameters:** - `search` - Text search on action field (ILIKE) - `category` - Filter by category (auth, vehicle, user, system, admin) - `severity` - Filter by severity (info, warning, error) - `startDate` - ISO date string for date range start - `endDate` - ISO date string for date range end - `limit` - Page size (default 25, max 100) - `offset` - Pagination offset **Response:** ```json { "logs": [ { "id": "uuid", "category": "vehicle", "severity": "info", "userId": "auth0|...", "action": "Vehicle created: 2024 Toyota Camry", "resourceType": "vehicle", "resourceId": "vehicle-uuid", "details": { "vin": "...", "make": "Toyota" }, "createdAt": "2024-01-15T10:30:00Z" } ], "total": 150, "limit": 25, "offset": 0 } ``` ### GET /api/admin/audit-logs/export Returns CSV file with filtered audit logs. **Query Parameters:** Same as list endpoint (except pagination) **Response:** CSV file download ## Usage in Features ```typescript import { auditLogService } from '../../audit-log'; // In vehicles.service.ts await auditLogService.info( 'vehicle', userId, `Vehicle created: ${vehicleDesc}`, 'vehicle', vehicleId, { vin, make, model, year } ).catch(err => logger.error('Failed to log audit event', { error: err })); ``` ## Retention Policy - Logs older than 90 days are automatically deleted - Cleanup job runs daily at 3 AM - Implemented in `jobs/cleanup.job.ts` ## Categories | Category | Description | Examples | |----------|-------------|----------| | `auth` | Authentication events | Signup, password reset | | `vehicle` | Vehicle CRUD | Create, update, delete | | `user` | User management | Profile updates | | `system` | System operations | Backup, restore | | `admin` | Admin actions | Grant/revoke admin | ## Severity Levels | Level | Color (UI) | Description | |-------|------------|-------------| | `info` | Blue | Normal operations | | `warning` | Yellow | Potential issues | | `error` | Red | Failed operations |