Spaces:
Sleeping
Sleeping
Create services/security.py
Browse files- services/security.py +18 -0
services/security.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# services/security.py
|
| 2 |
+
from fastapi import Security, HTTPException, status
|
| 3 |
+
from fastapi.security import APIKeyHeader
|
| 4 |
+
import config
|
| 5 |
+
|
| 6 |
+
API_KEY_NAME = "X-API-Key"
|
| 7 |
+
api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=True)
|
| 8 |
+
|
| 9 |
+
async def get_api_key(api_key: str = Security(api_key_header)):
|
| 10 |
+
"""Dependency to validate API Key."""
|
| 11 |
+
if config.ALLOWED_API_KEYS and api_key not in config.ALLOWED_API_KEYS:
|
| 12 |
+
raise HTTPException(
|
| 13 |
+
status_code=status.HTTP_403_FORBIDDEN,
|
| 14 |
+
detail="Invalid or missing API Key"
|
| 15 |
+
)
|
| 16 |
+
# If ALLOWED_API_KEYS is empty, allow all requests (useful for local dev or internal use)
|
| 17 |
+
# Consider adding a specific flag for this behaviour if needed for clarity
|
| 18 |
+
return api_key
|