38 lines
1.1 KiB
Python
38 lines
1.1 KiB
Python
"""Shared dependencies: the database session and the optional shared secret."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import Annotated
|
|
|
|
from fastapi import Depends, Header, HTTPException, status
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.config import env_settings
|
|
from app.db import get_session
|
|
from app.services.settings_service import load_settings
|
|
from app.settings_schema import AppSettings
|
|
|
|
DbSession = Annotated[Session, Depends(get_session)]
|
|
|
|
|
|
def require_token(x_api_token: Annotated[str | None, Header()] = None) -> None:
|
|
"""Guard every API call when `API_TOKEN` is set.
|
|
|
|
Off by default: on a laptop the backend is bound to localhost and a token is
|
|
friction. Set it the moment the container is reachable from anywhere else.
|
|
"""
|
|
expected = env_settings().api_token
|
|
if not expected:
|
|
return
|
|
if x_api_token != expected:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED, detail="Bad or missing X-API-Token."
|
|
)
|
|
|
|
|
|
def get_settings(session: DbSession) -> AppSettings:
|
|
return load_settings(session)
|
|
|
|
|
|
Settings = Annotated[AppSettings, Depends(get_settings)]
|