""" 平台对外 API 鉴权依赖 外部系统通过 Authorization: Bearer sk-aigc-xxx 调用对外接口时使用 """ from fastapi import Depends, HTTPException, status from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from sqlalchemy.orm import Session from app.database import get_db from app.services.platform_api_key_service import PlatformApiKeyService bearer_scheme = HTTPBearer(auto_error=False) def get_platform_caller( credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme), db: Session = Depends(get_db), ) -> str: """ 验证平台 API Key,返回调用方 user_id。 请求头格式:Authorization: Bearer sk-aigc-xxxxxxxx """ if not credentials or not credentials.credentials: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="缺少 Authorization 请求头", headers={"WWW-Authenticate": "Bearer"}, ) result = PlatformApiKeyService(db).verify_api_key(credentials.credentials) if not result: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="API Key 无效或已禁用", headers={"WWW-Authenticate": "Bearer"}, ) user_id, _ = result return user_id