7a7daf8100
- 10 models: tenants, users, user_tenants, roles, sessions, audit_log, deletion_log, notifications, password_reset_tokens, api_tokens - Session-based auth (Redis + PostgreSQL audit trail) - Multi-tenant with ORM-level filtering + PostgreSQL RLS (set_config) - RBAC with roles/permissions + field-level permissions - CSRF protection via Origin header validation - Auth rate limiting (Redis counters with TTL) - CORS with explicit origins (no wildcard) - Health endpoint (no auth required) - Notification service + audit log middleware - 29 tests, 26 ACs, all passing - Coverage: 62% (infrastructure modules pending coverage in later tasks)
55 lines
1.2 KiB
Python
55 lines
1.2 KiB
Python
"""Audit log middleware — records create/update/delete actions."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import uuid
|
|
from typing import Any
|
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.models.audit import AuditLog, DeletionLog
|
|
|
|
|
|
async def log_audit(
|
|
db: AsyncSession,
|
|
tenant_id: uuid.UUID,
|
|
user_id: uuid.UUID | None,
|
|
action: str,
|
|
entity_type: str,
|
|
entity_id: uuid.UUID | None = None,
|
|
changes: dict[str, Any] | None = None,
|
|
) -> AuditLog:
|
|
"""Create an audit log entry."""
|
|
entry = AuditLog(
|
|
tenant_id=tenant_id,
|
|
user_id=user_id,
|
|
action=action,
|
|
entity_type=entity_type,
|
|
entity_id=entity_id,
|
|
changes=changes,
|
|
)
|
|
db.add(entry)
|
|
await db.flush()
|
|
return entry
|
|
|
|
|
|
async def log_deletion(
|
|
db: AsyncSession,
|
|
tenant_id: uuid.UUID,
|
|
user_id: uuid.UUID | None,
|
|
entity_type: str,
|
|
entity_id: uuid.UUID,
|
|
entity_snapshot: dict[str, Any],
|
|
) -> DeletionLog:
|
|
"""Create a deletion log entry (immutable snapshot)."""
|
|
entry = DeletionLog(
|
|
tenant_id=tenant_id,
|
|
user_id=user_id,
|
|
entity_type=entity_type,
|
|
entity_id=entity_id,
|
|
entity_snapshot=entity_snapshot,
|
|
)
|
|
db.add(entry)
|
|
await db.flush()
|
|
return entry
|