This commit is contained in:
薇薇安 2026-01-20 22:17:09 +08:00
parent ad63dbd234
commit 1fdcb9c8b7

View File

@ -4,7 +4,8 @@ FastAPI 依赖:解析 JWT、获取当前用户、校验 admin、校验 account
from __future__ import annotations
from fastapi import Header, HTTPException, Depends
from fastapi import Header, HTTPException, Depends, Security
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from typing import Optional, Dict, Any
import os
@ -17,14 +18,21 @@ def _auth_enabled() -> bool:
return v not in {"0", "false", "no"}
def get_current_user(authorization: Optional[str] = Header(None, alias="Authorization")) -> Dict[str, Any]:
_bearer_scheme = HTTPBearer(auto_error=False)
def get_current_user(credentials: Optional[HTTPAuthorizationCredentials] = Security(_bearer_scheme)) -> Dict[str, Any]:
if not _auth_enabled():
# 未启用登录:视为超级管理员(兼容开发/灰度)
return {"id": 0, "username": "dev", "role": "admin", "status": "active"}
if not authorization or not authorization.lower().startswith("bearer "):
if not credentials:
raise HTTPException(status_code=401, detail="未登录")
if (credentials.scheme or "").lower() != "bearer":
raise HTTPException(status_code=401, detail="未登录")
token = (credentials.credentials or "").strip()
if not token:
raise HTTPException(status_code=401, detail="未登录")
token = authorization.split(" ", 1)[1].strip()
try:
payload = jwt_decode(token)
except Exception: