stock-data-api / app /core /security.py
fromozuzhouzzz
Apply fixes: search SSE streaming, fund-flow fallback, default search config
5c9b605
Raw
History Blame Contribute Delete
757 Bytes
"""Optional API key protection."""
from __future__ import annotations
from fastapi import HTTPException, Request, status
from app.core.config import settings
async def require_api_key(request: Request) -> None:
"""Require X-API-Key or Bearer token when STOCK_DATA_API_KEY is configured."""
if not settings.api_key:
return
header_key = request.headers.get("X-API-Key", "")
auth = request.headers.get("Authorization", "")
bearer_key = auth.removeprefix("Bearer ").strip() if auth.startswith("Bearer ") else ""
if header_key == settings.api_key or bearer_key == settings.api_key:
return
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Missing or invalid API key",
)