添加日志

This commit is contained in:
ChengCan
2026-03-26 11:25:34 +08:00
parent 3e3f4390a6
commit cff7ddf220
9 changed files with 351 additions and 4 deletions

View File

@@ -1,4 +1,5 @@
from collections.abc import Awaitable, Callable
import logging
from fastapi import FastAPI, HTTPException, Request
from sqlalchemy import text
@@ -21,6 +22,8 @@ EXCLUDED_PATH_PREFIXES = (
"/auth/login",
)
logger = logging.getLogger("app.auth")
def _is_excluded_path(path: str) -> bool:
for prefix in EXCLUDED_PATH_PREFIXES:
@@ -41,15 +44,42 @@ def install_auth_middleware(app: FastAPI) -> None:
auth_header = request.headers.get("Authorization")
if not auth_header:
logger.warning(
"auth failed: missing header",
extra={
"event": "auth_check",
"request_id": getattr(request.state, "request_id", None),
"path": path,
"reason": "missing_authorization_header",
},
)
return auth_error_response("missing authorization header")
parts = auth_header.split(" ", 1)
if len(parts) != 2 or parts[0].lower() != "bearer":
logger.warning(
"auth failed: invalid header format",
extra={
"event": "auth_check",
"request_id": getattr(request.state, "request_id", None),
"path": path,
"reason": "invalid_authorization_format",
},
)
return auth_error_response("invalid authorization format")
try:
user_id = decode_access_token(parts[1].strip())
except HTTPException:
logger.warning(
"auth failed: invalid token",
extra={
"event": "auth_check",
"request_id": getattr(request.state, "request_id", None),
"path": path,
"reason": "invalid_or_expired_token",
},
)
return auth_error_response("invalid or expired access token")
with SessionLocal() as db:
@@ -69,6 +99,16 @@ def install_auth_middleware(app: FastAPI) -> None:
.first()
)
if not user_row or int(user_row["status"]) != 1:
logger.warning(
"auth failed: user unavailable",
extra={
"event": "auth_check",
"request_id": getattr(request.state, "request_id", None),
"path": path,
"user_id": user_id,
"reason": "user_not_found_or_disabled",
},
)
return auth_error_response("user not found or disabled")
request.state.user_id = user_id