Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
| """ | |
| Simple API Key Authentication for Private Deployment | |
| """ | |
| import os | |
| from fastapi import HTTPException, Security, status | |
| from fastapi.security import APIKeyHeader | |
| from typing import Optional | |
| # Get API key from environment variable | |
| API_KEY = os.getenv("API_KEY", None) | |
| # Create API key header scheme | |
| api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False) | |
| async def verify_api_key(api_key: Optional[str] = Security(api_key_header)) -> bool: | |
| """ | |
| Verify API key if one is configured | |
| If no API_KEY is set in environment, allows all requests (public mode) | |
| If API_KEY is set, requires matching key in X-API-Key header | |
| """ | |
| # If no API key is configured, allow all requests (public mode) | |
| if not API_KEY: | |
| return True | |
| # If API key is configured but not provided in request | |
| if not api_key: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="API Key required" | |
| ) | |
| # Verify the API key | |
| if api_key != API_KEY: | |
| raise HTTPException( | |
| status_code=status.HTTP_403_FORBIDDEN, | |
| detail="Invalid API Key" | |
| ) | |
| return True |