Spaces:
Running
Running
File size: 757 Bytes
5c9b605 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | """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",
)
|