|
| 1 | +"""Admin router — privileged actions and the audit-log query API. |
| 2 | +
|
| 3 | +Every state-changing endpoint here is gated behind :func:`require_admin` and |
| 4 | +records an append-only entry via :func:`record_audit`, giving a tamper-evident |
| 5 | +trail of who did what and when. |
| 6 | +""" |
| 7 | + |
| 8 | +import json |
| 9 | + |
| 10 | +from fastapi import APIRouter, Depends, HTTPException, Query, Request, status |
| 11 | +from sqlalchemy import select |
| 12 | +from sqlalchemy.orm import Session |
| 13 | + |
| 14 | +from ..database import get_db |
| 15 | +from ..models import AuditLog, User |
| 16 | +from ..schemas import AuditLogRecord, MessageResponse, RoleUpdateRequest |
| 17 | +from ..security import require_admin |
| 18 | +from ..services.audit import record_audit |
| 19 | + |
| 20 | +router = APIRouter(prefix="/admin", tags=["Admin"]) |
| 21 | + |
| 22 | + |
| 23 | +def _client_ip(request: Request) -> str | None: |
| 24 | + return request.client.host if request.client else None |
| 25 | + |
| 26 | + |
| 27 | +def _to_record(entry: AuditLog) -> AuditLogRecord: |
| 28 | + return AuditLogRecord( |
| 29 | + id=entry.id, |
| 30 | + actor_id=entry.actor_id, |
| 31 | + actor_email=entry.actor_email, |
| 32 | + action=entry.action, |
| 33 | + target_type=entry.target_type, |
| 34 | + target_id=entry.target_id, |
| 35 | + details=json.loads(entry.details) if entry.details else None, |
| 36 | + ip_address=entry.ip_address, |
| 37 | + created_at=entry.created_at.isoformat(), |
| 38 | + ) |
| 39 | + |
| 40 | + |
| 41 | +@router.get("/audit-logs", response_model=list[AuditLogRecord]) |
| 42 | +def list_audit_logs( |
| 43 | + action: str | None = Query(None, description="Filter by exact action name."), |
| 44 | + actor_id: int | None = Query(None, description="Filter by acting admin's id."), |
| 45 | + limit: int = Query(50, ge=1, le=200), |
| 46 | + offset: int = Query(0, ge=0), |
| 47 | + _admin: User = Depends(require_admin), |
| 48 | + db: Session = Depends(get_db), |
| 49 | +): |
| 50 | + """Return audit entries, newest first. Admin only.""" |
| 51 | + query = select(AuditLog).order_by(AuditLog.id.desc()) |
| 52 | + if action is not None: |
| 53 | + query = query.where(AuditLog.action == action) |
| 54 | + if actor_id is not None: |
| 55 | + query = query.where(AuditLog.actor_id == actor_id) |
| 56 | + |
| 57 | + entries = db.execute(query.limit(limit).offset(offset)).scalars().all() |
| 58 | + return [_to_record(entry) for entry in entries] |
| 59 | + |
| 60 | + |
| 61 | +@router.put("/users/{user_id}/role", response_model=MessageResponse) |
| 62 | +def update_user_role( |
| 63 | + user_id: int, |
| 64 | + payload: RoleUpdateRequest, |
| 65 | + request: Request, |
| 66 | + admin: User = Depends(require_admin), |
| 67 | + db: Session = Depends(get_db), |
| 68 | +): |
| 69 | + """Grant or revoke a user's admin role, recording the change in the audit log.""" |
| 70 | + user = db.get(User, user_id) |
| 71 | + if user is None: |
| 72 | + raise HTTPException( |
| 73 | + status_code=status.HTTP_404_NOT_FOUND, detail="User not found" |
| 74 | + ) |
| 75 | + |
| 76 | + previous = user.is_admin |
| 77 | + user.is_admin = payload.is_admin |
| 78 | + record_audit( |
| 79 | + db, |
| 80 | + actor=admin, |
| 81 | + action="user.role_update", |
| 82 | + target_type="user", |
| 83 | + target_id=user.id, |
| 84 | + details={"from": previous, "to": payload.is_admin, "email": user.email}, |
| 85 | + ip_address=_client_ip(request), |
| 86 | + ) |
| 87 | + db.commit() |
| 88 | + return MessageResponse( |
| 89 | + message=f"User {user_id} admin role set to {payload.is_admin}." |
| 90 | + ) |
| 91 | + |
| 92 | + |
| 93 | +@router.delete("/users/{user_id}", response_model=MessageResponse) |
| 94 | +def delete_user( |
| 95 | + user_id: int, |
| 96 | + request: Request, |
| 97 | + admin: User = Depends(require_admin), |
| 98 | + db: Session = Depends(get_db), |
| 99 | +): |
| 100 | + """Delete a user account, recording the action in the audit log.""" |
| 101 | + if user_id == admin.id: |
| 102 | + raise HTTPException( |
| 103 | + status_code=status.HTTP_400_BAD_REQUEST, |
| 104 | + detail="Admins cannot delete their own account", |
| 105 | + ) |
| 106 | + |
| 107 | + user = db.get(User, user_id) |
| 108 | + if user is None: |
| 109 | + raise HTTPException( |
| 110 | + status_code=status.HTTP_404_NOT_FOUND, detail="User not found" |
| 111 | + ) |
| 112 | + |
| 113 | + email = user.email |
| 114 | + db.delete(user) |
| 115 | + record_audit( |
| 116 | + db, |
| 117 | + actor=admin, |
| 118 | + action="user.delete", |
| 119 | + target_type="user", |
| 120 | + target_id=user_id, |
| 121 | + details={"email": email}, |
| 122 | + ip_address=_client_ip(request), |
| 123 | + ) |
| 124 | + db.commit() |
| 125 | + return MessageResponse(message=f"User {user_id} deleted.") |
0 commit comments