Spaces:
Paused

miracle / core /audit.py
dushyantsingh0
fix: resolve typescript build errors in internal portal navigation
b0867f8
Raw History Blame Contribute Delete
1.54 kB
from typing import Any, Dict, Optional
from uuid import UUID
from datetime import datetime
from core.database import async_session_factory
from core.logging import get_logger
from models.audit_log import AuditLog
logger = get_logger(__name__)
async def log_security_event(
workspace_id: UUID,
entity_type: str,
entity_id: UUID,
action: str,
user_id: Optional[UUID] = None,
old_value: Optional[Dict[str, Any]] = None,
new_value: Optional[Dict[str, Any]] = None,
metadata_json: Optional[Dict[str, Any]] = None
):
"""
Logs a security-sensitive event to the audit_logs table.
Can be used directly or passed to BackgroundTasks.
"""
try:
async with async_session_factory() as db:
log_entry = AuditLog(
workspace_id=workspace_id,
entity_type=entity_type,
entity_id=entity_id,
action=action,
user_id=user_id,
old_value=old_value,
new_value=new_value,
metadata_json=metadata_json or {}
)
db.add(log_entry)
await db.commit()
logger.info(f"🛡️ [SECURITY AUDIT] {action.upper()} | Entity: {entity_type} ({entity_id}) | Actor: {user_id}")
except Exception as e:
logger.error(f"Failed to write security audit log: {str(e)}")
def log_action(background_tasks, **kwargs):
"""Helper to queue audit logs in background tasks."""
background_tasks.add_task(log_security_event, **kwargs)