-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdependencies.py
More file actions
31 lines (27 loc) · 1.11 KB
/
Copy pathdependencies.py
File metadata and controls
31 lines (27 loc) · 1.11 KB
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
26
27
28
29
30
31
import os
import secrets
from fastapi import HTTPException, Security
from fastapi.security import APIKeyHeader, APIKeyQuery
# Generate a fallback if missing so the scheduler can still authenticate
ADMIN_KEY = os.environ.get("ADMIN_KEY")
if not ADMIN_KEY:
ADMIN_KEY = secrets.token_urlsafe(32)
print("WARNING: ADMIN_KEY not set in .env. A secure random fallback has been generated for this session.")
api_key_header = APIKeyHeader(name="X-Admin-Key", auto_error=False)
api_key_query = APIKeyQuery(name="admin_key", auto_error=False)
async def verify_admin_token(
header_key: str = Security(api_key_header),
query_key: str = Security(api_key_query)
):
"""
Validates that the provided admin key (either via header or query param)
matches the securely stored ADMIN_KEY environment variable.
"""
if header_key and secrets.compare_digest(header_key, ADMIN_KEY):
return header_key
if query_key and secrets.compare_digest(query_key, ADMIN_KEY):
return query_key
raise HTTPException(
status_code=403,
detail="Unauthorized. Invalid or missing Admin Key."
)