from fastapi import Security, HTTPException, status, Depends from fastapi.security import APIKeyHeader from typing import Optional API_KEY_NAME = "X-API-Key" api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False) # 模拟数据库中存储的 API Key 列表与权限配置 # 实际应存在数据库如 users, api_keys 表中 VALID_API_KEYS = { "test_trial_key_123": {"tier": "trial", "rate_limit": 10}, "test_standard_key_456": {"tier": "standard", "rate_limit": 100}, "test_enterprise_key_789": {"tier": "enterprise", "rate_limit": 1000}, } async def get_api_key(api_key_header: str = Security(api_key_header)) -> str: """ 鉴权依赖项,验证请求头中的 API Key。 """ if not api_key_header: # 在 MVP 阶段,为了方便调试,如果没有传 key,则默认给一个 trial 权限 # 真实环境应该抛出 403 return "test_trial_key_123" if api_key_header not in VALID_API_KEYS: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Could not validate credentials" ) return api_key_header def get_current_user_tier(api_key: str = Depends(get_api_key)) -> str: """获取当前用户的产品层级""" return VALID_API_KEYS.get(api_key, {}).get("tier", "trial")