auth.py 517 B

12345678910111213141516
  1. """API 鉴权依赖."""
  2. import os
  3. from fastapi import Header, HTTPException, status
  4. from config.device import DEVICE_CONFIG
  5. def verify_api_key(x_api_key: str = Header(None)) -> None:
  6. """验证 API Key;未配置时允许访问(向后兼容本地开发)."""
  7. expected = DEVICE_CONFIG.get("api_key") or os.environ.get("API_KEY")
  8. if expected and x_api_key != expected:
  9. raise HTTPException(
  10. status_code=status.HTTP_401_UNAUTHORIZED,
  11. detail="Invalid API key",
  12. )