File size: 796 Bytes
b657fcc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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")