133 lines
4.9 KiB
Python
133 lines
4.9 KiB
Python
"""ASGI middleware: 统一请求上下文 + 操作日志落库."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import time
|
||
from typing import Awaitable, Callable
|
||
|
||
from starlette.middleware.base import BaseHTTPMiddleware
|
||
from starlette.requests import Request
|
||
from starlette.responses import Response
|
||
from starlette.types import ASGIApp
|
||
|
||
from ..db.session import SessionFactory
|
||
from ..models.rbac import OperationLog
|
||
|
||
SKIP_PATHS = ("/health", "/api/v1/common/health", "/docs", "/openapi.json", "/redoc")
|
||
SKIP_PREFIXES = ("/uploads", "/static")
|
||
# 这些路径的写操作不记日志(登录自带账号日志、高频只读接口)
|
||
READ_METHODS = {"GET", "HEAD", "OPTIONS"}
|
||
|
||
MODULE_BY_SEGMENT = {
|
||
"auth": "认证",
|
||
"org": "组织架构",
|
||
"system": "系统管理",
|
||
"employees": "人事档案",
|
||
"employee": "人事档案",
|
||
"recruitment": "招聘管理",
|
||
"payroll": "薪资管理",
|
||
"benefits": "福利保险",
|
||
"self": "员工自助",
|
||
"dashboard": "工作台",
|
||
"common": "公共服务",
|
||
}
|
||
|
||
ACTION_BY_METHOD = {"POST": "create", "PUT": "update", "PATCH": "update", "DELETE": "delete"}
|
||
|
||
|
||
def _module_of(path: str) -> str:
|
||
parts = [p for p in path.split("/") if p]
|
||
for part in parts:
|
||
if part in MODULE_BY_SEGMENT:
|
||
return MODULE_BY_SEGMENT[part]
|
||
return parts[0] if parts else "other"
|
||
|
||
|
||
def _action_of(path: str, method: str) -> str:
|
||
tail = [p for p in path.split("/") if p]
|
||
if tail:
|
||
last = tail[-1]
|
||
if not last.isdigit() and last not in MODULE_BY_SEGMENT:
|
||
if method == "GET":
|
||
return last if last.isalpha() and len(last) < 24 else "read"
|
||
return last if last.isalpha() and len(last) < 24 else ACTION_BY_METHOD.get(method, method)
|
||
if method in READ_METHODS:
|
||
return "read"
|
||
return ACTION_BY_METHOD.get(method, method.lower())
|
||
|
||
|
||
def _should_log(path: str, method: str) -> bool:
|
||
if path in SKIP_PATHS or any(path.startswith(p) for p in SKIP_PREFIXES):
|
||
return False
|
||
if method in READ_METHODS:
|
||
# 只记录少量高风险查询,避免日志爆炸
|
||
return False
|
||
return True
|
||
|
||
|
||
class OperationLogMiddleware(BaseHTTPMiddleware):
|
||
"""记录所有写操作(POST/PUT/PATCH/DELETE)到 ``sys_operation_log``。"""
|
||
|
||
def __init__(self, app: ASGIApp, *, log_reads: bool = False) -> None:
|
||
super().__init__(app)
|
||
self.log_reads = log_reads
|
||
|
||
async def dispatch(self, request: Request, call_next: Callable[[Request], Awaitable[Response]]) -> Response:
|
||
started = time.perf_counter()
|
||
response: Response
|
||
status_code = 500
|
||
try:
|
||
response = await call_next(request)
|
||
status_code = response.status_code
|
||
except Exception:
|
||
status_code = 500
|
||
if not _should_log(request.url.path, request.method) and not self.log_reads:
|
||
raise
|
||
await self._persist(request, status_code, started)
|
||
raise
|
||
path = request.url.path
|
||
should = _should_log(path, request.method) or (self.log_reads and request.method in READ_METHODS)
|
||
if should:
|
||
await self._persist(request, status_code, started)
|
||
return response
|
||
|
||
async def _persist(self, request: Request, status_code: int, started: float) -> None:
|
||
duration = int((time.perf_counter() - started) * 1000)
|
||
ctx = getattr(request.state, "auth_context", None)
|
||
user = getattr(ctx, "user", None) if ctx is not None else None
|
||
detail = str(request.query_params) or None
|
||
client = request.client.host if request.client else None
|
||
forwarded = request.headers.get("x-forwarded-for")
|
||
if forwarded:
|
||
client = forwarded.split(",")[0].strip()
|
||
try:
|
||
async with SessionFactory() as session:
|
||
session.add(OperationLog(
|
||
user_id=getattr(user, "id", None),
|
||
username=getattr(user, "username", None),
|
||
module=_module_of(request.url.path),
|
||
action=_action_of(request.url.path, request.method),
|
||
method=request.method,
|
||
path=request.url.path[:255],
|
||
ip=client,
|
||
status_code=status_code,
|
||
duration_ms=duration,
|
||
detail=detail[:255] if detail else None,
|
||
))
|
||
await session.commit()
|
||
except Exception: # pragma: no cover - 日志失败绝不影响业务
|
||
pass
|
||
|
||
|
||
class RequestIdMiddleware(BaseHTTPMiddleware):
|
||
"""为每个请求附带 x-request-id,便于排查。"""
|
||
|
||
async def dispatch(self, request: Request, call_next) -> Response:
|
||
import uuid
|
||
|
||
rid = request.headers.get("x-request-id") or uuid.uuid4().hex[:12]
|
||
request.state.request_id = rid
|
||
response = await call_next(request)
|
||
response.headers["x-request-id"] = rid
|
||
return response
|