Axiovora-X / backend /auth.py
ZAIDX11's picture
Add files using upload-large-folder tool
b657fcc verified
from .config import get_env
def require_token(x_api_key: str | None = None):
"""Check the API token. Does not import FastAPI at module import time so
tests can run when a repo-local `fastapi/` folder is present. If FastAPI is
available at runtime, raise an HTTPException to produce a proper 401 for
API endpoints; otherwise raise PermissionError for programmatic callers.
"""
expected = get_env("DEMO_API_TOKEN", "demo-token")
if x_api_key != expected:
try:
# import lazily so tests without FastAPI don't fail at import time
from fastapi import HTTPException
raise HTTPException(status_code=401, detail="Invalid API token")
except Exception:
raise PermissionError("Invalid API token")