233 lines
8.4 KiB
Markdown
233 lines
8.4 KiB
Markdown
# VitFit V2 — Audit Logs
|
|
|
|
## Purpose
|
|
|
|
Audit logs record who did what, when, and to which record. They serve two purposes:
|
|
1. **Security / compliance** — detect unauthorized changes, investigate incidents
|
|
2. **Operational accountability** — know who uploaded a video, who deleted a workout, who changed a password
|
|
|
|
Audit logs are **append-only**. No log record is ever updated or deleted.
|
|
|
|
---
|
|
|
|
## Event Catalog
|
|
|
|
### Authentication Events
|
|
|
|
| Action | Trigger | Details |
|
|
|--------|---------|---------|
|
|
| `auth.login.success` | Successful login | `{ username }` |
|
|
| `auth.login.failed` | Failed login attempt | `{ username, reason }` |
|
|
| `auth.logout` | Explicit logout | — |
|
|
| `auth.device.registered` | "Remember this device" issued | `{ deviceName, deviceType, expiresAt }` |
|
|
| `auth.device.revoked` | Device token revoked by admin | `{ deviceName, revokedBy }` |
|
|
| `auth.token.refreshed` | Silent JWT refresh via device token | — |
|
|
|
|
### User Management
|
|
|
|
| Action | Trigger | Details |
|
|
|--------|---------|---------|
|
|
| `user.create` | New user created | `{ after: { username, role } }` |
|
|
| `user.deactivate` | User deactivated | `{ before: { isActive: true }, after: { isActive: false } }` |
|
|
| `user.role.change` | Role changed | `{ before: { role }, after: { role } }` |
|
|
| `user.password.reset` | Admin resets a user's password | `{ targetUserId }` (no password in log) |
|
|
| `user.profile.update` | User updates own profile | `{ before: { firstName, lastName }, after: {...} }` |
|
|
| `coach.client.assign` | Coach assigned to client | `{ coachId, clientId }` |
|
|
| `coach.client.unassign` | Coach/client link removed | `{ coachId, clientId }` |
|
|
|
|
### Video Library
|
|
|
|
| Action | Trigger | Details |
|
|
|--------|---------|---------|
|
|
| `video.upload` | Video file uploaded | `{ filename, description, category, fileSizeBytes }` |
|
|
| `video.delete` | Video deleted | `{ before: { filename, description, category } }` |
|
|
| `category.create` | New category created | `{ name }` |
|
|
| `category.delete` | Category deleted | `{ before: { name } }` |
|
|
|
|
### Group Workouts
|
|
|
|
| Action | Trigger | Details |
|
|
|--------|---------|---------|
|
|
| `workout.create` | Workout created | `{ after: { name, workoutDate, videoIds } }` |
|
|
| `workout.delete` | Workout deleted | `{ before: { name, workoutDate } }` |
|
|
| `workout.display.launch` | Workout sent to TV display | `{ workoutId, name }` |
|
|
|
|
### Timers
|
|
|
|
| Action | Trigger | Details |
|
|
|--------|---------|---------|
|
|
| `timer.create` | Timer configuration created | `{ after: { name, totalTime, setTime, ... } }` |
|
|
| `timer.delete` | Timer deleted | `{ before: { name } }` |
|
|
| `timer.launch` | Timer started (sent to display) | `{ timerId, name }` |
|
|
| `timer.stop` | Running timer stopped early | `{ timerId, elapsedSeconds }` |
|
|
|
|
### CrossFit Workouts
|
|
|
|
| Action | Trigger | Details |
|
|
|--------|---------|---------|
|
|
| `crossfit.create` | CrossFit workout created | `{ after: { name, workoutDate, itemCount } }` |
|
|
| `crossfit.delete` | CrossFit workout deleted | `{ before: { name, workoutDate } }` |
|
|
|
|
### Client Workouts (1-on-1)
|
|
|
|
| Action | Trigger | Details |
|
|
|--------|---------|---------|
|
|
| `client_workout.create` | Workout created for client | `{ clientId, after: { name, scheduledDate } }` |
|
|
| `client_workout.update` | Workout modified | `{ clientId, before: {...}, after: {...} }` |
|
|
| `client_workout.delete` | Workout deleted | `{ clientId, before: { name } }` |
|
|
| `client_workout.complete` | Marked as completed | `{ clientId, workoutId }` |
|
|
|
|
### Calendar
|
|
|
|
| Action | Trigger | Details |
|
|
|--------|---------|---------|
|
|
| `session.create` | Session scheduled | `{ after: { clientId, startAt, endAt, type } }` |
|
|
| `session.update` | Session rescheduled or modified | `{ before: {...}, after: {...} }` |
|
|
| `session.cancel` | Session cancelled | `{ before: { startAt }, cancelledBy }` |
|
|
| `session.status.change` | Status updated (e.g., completed, no-show) | `{ before: { status }, after: { status } }` |
|
|
|
|
### Organization & Branding
|
|
|
|
| Action | Trigger | Details |
|
|
|--------|---------|---------|
|
|
| `org.create` | New organization created | `{ after: { name, slug } }` (SystemAdmin only) |
|
|
| `org.update` | Org settings changed | `{ before: {...}, after: {...} }` |
|
|
| `branding.update` | Logo/colors changed | `{ before: { primaryColor, ... }, after: {...} }` (logo path, not binary) |
|
|
| `logo.upload` | Logo file uploaded | `{ filename, fileSizeBytes }` |
|
|
|
|
### Storage / System
|
|
|
|
| Action | Trigger | Details |
|
|
|--------|---------|---------|
|
|
| `storage.warning` | Disk space drops below warn threshold | `{ available, threshold }` (system-generated) |
|
|
| `upload.rejected.storage` | Upload rejected due to low disk | `{ attemptedBy, availableBytes }` |
|
|
|
|
---
|
|
|
|
## Implementation
|
|
|
|
### Where Logs Are Written
|
|
|
|
Logs are written explicitly in route handlers, not via generic middleware. This is intentional — automatic middleware logging produces too much noise (every GET request) and misses the context (what changed, before/after values).
|
|
|
|
```js
|
|
// Example: video upload route
|
|
router.post('/upload', authenticateToken, upload.single('video'), async (req, res) => {
|
|
const video = await Video.create({ ... });
|
|
|
|
await AuditLog.create({
|
|
organizationId: req.user.organizationId,
|
|
userId: req.user.id,
|
|
userRole: req.user.role,
|
|
action: 'video.upload',
|
|
entityType: 'video',
|
|
entityId: video.id,
|
|
details: JSON.stringify({ filename: video.filename, category: video.category, fileSizeBytes: video.fileSizeBytes }),
|
|
ipAddress: req.ip,
|
|
userAgent: req.get('User-Agent'),
|
|
});
|
|
|
|
res.json(video);
|
|
});
|
|
```
|
|
|
|
A helper function keeps this concise:
|
|
```js
|
|
// core/audit.js
|
|
async function log(req, action, entityType, entityId, details = {}) {
|
|
await AuditLog.create({
|
|
organizationId: req.user?.organizationId ?? null,
|
|
userId: req.user?.id ?? null,
|
|
userRole: req.user?.role ?? 'system',
|
|
action,
|
|
entityType,
|
|
entityId,
|
|
details: JSON.stringify(details),
|
|
ipAddress: req.ip,
|
|
userAgent: req.get('User-Agent'),
|
|
});
|
|
}
|
|
module.exports = { log };
|
|
|
|
// Usage:
|
|
await audit.log(req, 'video.upload', 'video', video.id, { filename: video.filename });
|
|
```
|
|
|
|
### Failed Login Logging
|
|
|
|
Login failures need to be logged even when there's no `req.user`. The auth route handles this directly:
|
|
|
|
```js
|
|
router.post('/auth/login', loginRateLimiter, async (req, res) => {
|
|
const user = await User.findOne({ where: { username: req.body.username } });
|
|
|
|
if (!user || !await bcrypt.compare(req.body.password, user.password)) {
|
|
await AuditLog.create({
|
|
action: 'auth.login.failed',
|
|
details: JSON.stringify({ username: req.body.username, reason: user ? 'bad_password' : 'unknown_user' }),
|
|
ipAddress: req.ip,
|
|
userAgent: req.get('User-Agent'),
|
|
});
|
|
return res.sendStatus(401);
|
|
}
|
|
// ...
|
|
});
|
|
```
|
|
|
|
Note: `username` is logged on failed login (not password). This is useful for detecting brute-force attempts.
|
|
|
|
---
|
|
|
|
## API Endpoints
|
|
|
|
```
|
|
GET /audit-logs Owner: paginated log for their org
|
|
SystemAdmin: query param ?orgId= for cross-org
|
|
GET /audit-logs/export Download as CSV (Owner+ only)
|
|
```
|
|
|
|
Query params for `GET /audit-logs`:
|
|
- `?page=1&limit=50` — pagination
|
|
- `?action=video.upload` — filter by action
|
|
- `?userId=123` — filter by user
|
|
- `?from=2025-01-01&to=2025-12-31` — date range
|
|
- `?entityType=video` — filter by entity type
|
|
|
|
---
|
|
|
|
## Frontend (Audit Log Viewer)
|
|
|
|
Accessible from Owner panel and SystemAdmin panel.
|
|
|
|
Layout:
|
|
- Filterable table: timestamp, user, role, action, entity, details summary
|
|
- Expandable row: shows full `details` JSON formatted
|
|
- Filter bar: action type, date range, user dropdown
|
|
- "Export CSV" button
|
|
- Paginated (50 records per page, no infinite scroll — avoids memory issues on long sessions)
|
|
|
|
Color-code rows by action category:
|
|
- Auth events: blue
|
|
- Deletes: red
|
|
- Creates: green
|
|
- Updates: yellow
|
|
- System/storage: gray
|
|
|
|
---
|
|
|
|
## Retention
|
|
|
|
Audit logs are never automatically deleted. On a single-gym SQLite installation, logs are small (a few KB per entry) and accumulate slowly. Tens of thousands of entries are not a concern for SQLite.
|
|
|
|
If the table grows problematic (unlikely within a gym's operating lifespan), a SystemAdmin can export to CSV and truncate via a manual SQL operation — there is no automated purge in V2.
|
|
|
|
---
|
|
|
|
## What Is NOT Logged
|
|
|
|
- Successful read requests (too noisy, no value)
|
|
- Timer tick events (too frequent)
|
|
- Page views / navigation
|
|
- Failed requests due to auth (401/403) — except failed logins
|
|
- Health check endpoint calls
|