2026-06-29 00:10:10 +02:00
|
|
|
"""Audit log middleware — records create/update/delete actions."""
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
import uuid
|
|
|
|
|
from typing import Any
|
|
|
|
|
|
|
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
|
|
2026-08-06 13:23:58 +02:00
|
|
|
from app.models.audit import AuditLog
|
|
|
|
|
from app.models.entity_history import EntityHistory
|
2026-06-29 00:10:10 +02:00
|
|
|
|
|
|
|
|
|
|
|
|
|
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,
|
2026-08-12 20:47:43 +02:00
|
|
|
details: dict[str, Any] | None = None,
|
2026-06-29 00:10:10 +02:00
|
|
|
) -> AuditLog:
|
2026-08-13 20:39:32 +02:00
|
|
|
"""Create an audit log entry.
|
|
|
|
|
|
|
|
|
|
Sensitive fields in *changes* are masked using the central
|
|
|
|
|
:mod:`app.core.sensitive_data` module.
|
|
|
|
|
"""
|
|
|
|
|
from app.core.sensitive_data import sanitize_dict
|
|
|
|
|
|
|
|
|
|
masked_changes = sanitize_dict(changes, entity_type) if changes else changes
|
2026-06-29 00:10:10 +02:00
|
|
|
entry = AuditLog(
|
|
|
|
|
tenant_id=tenant_id,
|
|
|
|
|
user_id=user_id,
|
|
|
|
|
action=action,
|
|
|
|
|
entity_type=entity_type,
|
|
|
|
|
entity_id=entity_id,
|
2026-08-13 20:39:32 +02:00
|
|
|
changes=masked_changes,
|
2026-06-29 00:10:10 +02:00
|
|
|
)
|
|
|
|
|
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],
|
2026-08-06 13:23:58 +02:00
|
|
|
) -> EntityHistory:
|
|
|
|
|
"""Create a deletion history entry (merged from DeletionLog into EntityHistory).
|
|
|
|
|
|
|
|
|
|
Stores the full entity snapshot in snapshot_before for forensic recovery.
|
2026-08-13 20:39:32 +02:00
|
|
|
Sensitive fields are masked using the central
|
|
|
|
|
:mod:`app.core.sensitive_data` module.
|
2026-08-06 13:23:58 +02:00
|
|
|
"""
|
2026-08-13 20:39:32 +02:00
|
|
|
from app.core.sensitive_data import sanitize_dict
|
|
|
|
|
|
|
|
|
|
masked_snapshot = sanitize_dict(entity_snapshot, entity_type)
|
2026-08-06 13:23:58 +02:00
|
|
|
entry = EntityHistory(
|
2026-06-29 00:10:10 +02:00
|
|
|
tenant_id=tenant_id,
|
|
|
|
|
user_id=user_id,
|
|
|
|
|
entity_type=entity_type,
|
|
|
|
|
entity_id=entity_id,
|
2026-08-06 13:23:58 +02:00
|
|
|
action="delete",
|
2026-08-13 20:39:32 +02:00
|
|
|
snapshot_before=masked_snapshot,
|
2026-08-06 13:23:58 +02:00
|
|
|
snapshot_after=None,
|
|
|
|
|
changes=None,
|
|
|
|
|
owner_id=user_id,
|
2026-06-29 00:10:10 +02:00
|
|
|
)
|
|
|
|
|
db.add(entry)
|
|
|
|
|
await db.flush()
|
|
|
|
|
return entry
|