119 lines
4.2 KiB
Python
119 lines
4.2 KiB
Python
"""操作审计:谁在什么时候改了哪个菜单的数据,成功还是被拒。
|
||
|
||
写入口只有一个:`/api` 子应用上的 HTTP 中间件。它在每个请求结束后落一行,
|
||
所以 401/403(越权尝试)和 4xx/5xx(失败的写操作)同样留痕。
|
||
只记写操作 + 登录/退出,GET 不落库,避免日志被列表刷新刷爆。
|
||
业务代码可以用 `audit.note(request, "……")` 补一句说明,日志的「说明」列直接可读。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
from datetime import timedelta
|
||
|
||
from fastapi import Request
|
||
from sqlalchemy.orm import Session
|
||
|
||
from .db import SessionLocal
|
||
from .models import AuditLog, now
|
||
|
||
# 命中这些路径前缀的 GET 也要留痕(登录相关)
|
||
TRACKED_GETS = ()
|
||
# 方法 → 动作
|
||
METHOD_ACTION = {"POST": "create", "PUT": "update", "PATCH": "update", "DELETE": "delete"}
|
||
# 特殊动作:路径以这些结尾时按语义记,不套 method 默认值
|
||
SPECIAL_ACTION = {
|
||
"/api/auth/login": "login",
|
||
"/api/auth/logout": "logout",
|
||
"/api/auth/password": "password",
|
||
}
|
||
KEEP_DAYS = 180 # 日志保留天数,启动时清一次
|
||
|
||
|
||
def client_ip(request: Request) -> str | None:
|
||
fwd = request.headers.get("x-forwarded-for")
|
||
if fwd:
|
||
return fwd.split(",")[0].strip()[:64]
|
||
return request.client.host[:64] if request.client else None
|
||
|
||
|
||
def action_for(path: str, method: str) -> str | None:
|
||
"""返回 None 表示这个请求不进审计。"""
|
||
clean = path.rstrip("/")
|
||
if clean in SPECIAL_ACTION:
|
||
return SPECIAL_ACTION[clean]
|
||
if method in METHOD_ACTION:
|
||
return METHOD_ACTION[method]
|
||
if clean.endswith("/revoke") or clean.endswith("/purge"):
|
||
return "revoke"
|
||
return None
|
||
|
||
|
||
def note(request: Request, text: str | None = None, *, username: str | None = None) -> None:
|
||
"""业务代码给审计日志留一句人话说明;落库由中间件完成。
|
||
|
||
`username` 只在拿不到登录用户时用得上(比如密码输错,操作人记的是被尝试的账号)。
|
||
"""
|
||
try:
|
||
if text:
|
||
request.state.audit_detail = text[:255]
|
||
if username:
|
||
request.state.audit_username = username[:64]
|
||
except Exception: # 审计说明是锦上添花,不能带崩业务
|
||
pass
|
||
|
||
|
||
def write(db: Session, *, user, request: Request, status: int, action: str,
|
||
menu: str | None = None, detail: str | None = None,
|
||
username: str | None = None) -> None:
|
||
db.add(AuditLog(
|
||
user_id=getattr(user, "id", None),
|
||
username=username or getattr(user, "username", None),
|
||
action=action,
|
||
menu=menu,
|
||
method=request.method,
|
||
path=request.url.path[:255],
|
||
status=status,
|
||
ip=client_ip(request),
|
||
detail=detail[:255] if detail else None,
|
||
))
|
||
db.commit()
|
||
|
||
|
||
def prune(db: Session, keep_days: int = KEEP_DAYS) -> int:
|
||
q = db.query(AuditLog).filter(AuditLog.created_at < now() - timedelta(days=keep_days))
|
||
n = q.count()
|
||
if n:
|
||
q.delete(synchronize_session=False)
|
||
db.commit()
|
||
return n
|
||
|
||
|
||
def audit_middleware_factory():
|
||
"""给 /api 子应用用的中间件:写完响应后补一条审计。"""
|
||
|
||
async def audit(request: Request, call_next):
|
||
from .security import resolve_rule # 避免循环导入
|
||
|
||
action = action_for(request.url.path, request.method)
|
||
response = await call_next(request)
|
||
if action is None:
|
||
return response
|
||
path = request.url.path.rstrip("/")
|
||
rule = resolve_rule(path, request.method)
|
||
menu = rule[0] if rule else None
|
||
state = getattr(request, "state", None)
|
||
user = getattr(state, "user", None)
|
||
actor = getattr(state, "audit_username", None)
|
||
detail = getattr(state, "audit_detail", None)
|
||
if response.status_code >= 400:
|
||
detail = f"{detail};" if detail else ""
|
||
detail += f"HTTP {response.status_code}"
|
||
try:
|
||
with SessionLocal() as db:
|
||
write(db, user=user, request=request, status=response.status_code,
|
||
action=action, menu=menu, detail=detail, username=actor)
|
||
except Exception: # 审计绝不能把业务请求带崩
|
||
pass
|
||
return response
|
||
|
||
return audit
|