| from fastapi import HTTPException, Header, Depends |
| from fastapi.security import APIKeyHeader |
| from typing import Optional |
| from config import API_KEY |
|
|
| |
| def validate_api_key(api_key_to_validate: str) -> bool: |
| """ |
| Validate the provided API key against the configured key. |
| """ |
| if not API_KEY: |
| |
| |
| return False |
| return api_key_to_validate == API_KEY |
|
|
| |
| api_key_header = APIKeyHeader(name="Authorization", auto_error=False) |
|
|
| |
| async def get_api_key(authorization: Optional[str] = Header(None)): |
| if authorization is None: |
| raise HTTPException( |
| status_code=401, |
| detail="Missing API key. Please include 'Authorization: Bearer YOUR_API_KEY' header." |
| ) |
| |
| |
| if not authorization.startswith("Bearer "): |
| raise HTTPException( |
| status_code=401, |
| detail="Invalid API key format. Use 'Authorization: Bearer YOUR_API_KEY'" |
| ) |
| |
| |
| api_key = authorization.replace("Bearer ", "") |
| |
| |
| if not validate_api_key(api_key): |
| raise HTTPException( |
| status_code=401, |
| detail="Invalid API key" |
| ) |
| |
| return api_key |