feat:对接中心平台,完善接口鉴权
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
"""接口鉴权:从 Authorization 头取出用户中心 token,换取当前用户"""
|
||||
|
||||
from fastapi import Depends, Request
|
||||
|
||||
from app.clients.user_center import BEARER_CHALLENGE, UserCenterClient, get_user_center
|
||||
from app.config import settings
|
||||
from app.core.exceptions import BizException
|
||||
from app.schemas.user import CurrentUser
|
||||
|
||||
# AUTH_ENABLED=false 时所有请求共用的本地调试用户
|
||||
DEV_USER = CurrentUser(id=0, username="dev")
|
||||
|
||||
|
||||
def _bearer_token(request: Request) -> str:
|
||||
scheme, _, token = request.headers.get("Authorization", "").partition(" ")
|
||||
token = token.strip()
|
||||
if scheme.lower() != "bearer" or not token:
|
||||
raise BizException(401, "请先登录", BEARER_CHALLENGE)
|
||||
return token
|
||||
|
||||
|
||||
async def get_current_user(
|
||||
request: Request, client: UserCenterClient = Depends(get_user_center)
|
||||
) -> CurrentUser:
|
||||
"""同一请求内 FastAPI 会缓存结果,路由级和函数级重复声明只校验一次"""
|
||||
if not settings.auth_enabled:
|
||||
return DEV_USER
|
||||
return await client.fetch_current_user(_bearer_token(request))
|
||||
+13
-2
@@ -16,14 +16,25 @@ from app.exceptions import AppError, DecisionError
|
||||
class BizException(AppError):
|
||||
"""可安全返回给调用方的业务错误"""
|
||||
|
||||
def __init__(self, code: int, msg: str = "请求失败") -> None:
|
||||
def __init__(
|
||||
self,
|
||||
code: int,
|
||||
msg: str = "请求失败",
|
||||
headers: dict[str, str] | None = None,
|
||||
) -> None:
|
||||
self.code = code
|
||||
self.msg = msg
|
||||
# 协议响应头,例如 401 时的 WWW-Authenticate
|
||||
self.headers = headers
|
||||
super().__init__(msg)
|
||||
|
||||
|
||||
async def handle_biz_exception(_request: Request, exc: BizException) -> JSONResponse:
|
||||
return JSONResponse(status_code=exc.code, content=error_content(exc.code, exc.msg))
|
||||
return JSONResponse(
|
||||
status_code=exc.code,
|
||||
content=error_content(exc.code, exc.msg),
|
||||
headers=exc.headers,
|
||||
)
|
||||
|
||||
|
||||
async def handle_validation_exception(
|
||||
|
||||
Reference in New Issue
Block a user