50 lines
1.4 KiB
Python
50 lines
1.4 KiB
Python
# ///
|
|
# common.py
|
|
# 描述:公共工具函数和依赖注入
|
|
# 作者:AI Generated
|
|
# 创建日期:2026-04-05
|
|
# ///
|
|
|
|
from typing import Optional
|
|
from fastapi import Header, HTTPException, Depends
|
|
from config import get_settings
|
|
|
|
|
|
def require_api_key(x_api_key: Optional[str] = Header(None, alias="X-API-Key")):
|
|
"""
|
|
API Key 验证依赖
|
|
|
|
用于验证 X-API-Key Header 是否有效
|
|
|
|
Raises:
|
|
HTTPException: 401 - API Key 无效或缺失
|
|
|
|
Returns:
|
|
str: 有效的 API Key
|
|
"""
|
|
if not x_api_key:
|
|
raise HTTPException(status_code=401, detail="API Key required")
|
|
settings = get_settings()
|
|
if x_api_key != settings.external_api_key:
|
|
raise HTTPException(status_code=401, detail="Invalid API Key")
|
|
return x_api_key
|
|
|
|
|
|
def require_external_key(x_externalkey: Optional[str] = Header(None, alias="X-ExternalKey")):
|
|
"""
|
|
外部 API Key 验证依赖
|
|
|
|
用于验证 X-ExternalKey Header 是否有效
|
|
|
|
Raises:
|
|
HTTPException: 401 - External API Key 无效或缺失
|
|
|
|
Returns:
|
|
str: 有效的 External API Key
|
|
"""
|
|
if not x_externalkey:
|
|
raise HTTPException(status_code=401, detail="External API Key required")
|
|
settings = get_settings()
|
|
if x_externalkey != settings.external_api_key:
|
|
raise HTTPException(status_code=401, detail="Invalid External API Key")
|
|
return x_externalkey |