audit.py 965 B

123456789101112131415161718192021222324252627282930313233343536
  1. import json
  2. from typing import Any, Optional
  3. from flask import request
  4. from .core import isoformat, utcnow
  5. from .db import execute
  6. def audit(
  7. actor_type: str,
  8. actor_id: int,
  9. action: str,
  10. resource_type: str,
  11. resource_id: str,
  12. before: Optional[dict[str, Any]],
  13. after: Optional[dict[str, Any]],
  14. ) -> None:
  15. execute(
  16. """
  17. INSERT INTO audit_logs (actor_type, actor_id, action, resource_type, resource_id, before_json, after_json, ip, created_at)
  18. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
  19. """,
  20. (
  21. actor_type,
  22. actor_id,
  23. action,
  24. resource_type,
  25. resource_id,
  26. json.dumps(before, ensure_ascii=False) if before is not None else None,
  27. json.dumps(after, ensure_ascii=False) if after is not None else None,
  28. request.headers.get("X-Forwarded-For", request.remote_addr),
  29. isoformat(utcnow()),
  30. ),
  31. )