refactor(web): expose app settings as required/optional FastAPI deps
Mirror the session.py dependency trio: current_app_settings (honest optional accessor), get_app_settings (required; raises 500 if reached unconfigured), and set_app_settings (single write path). Middleware reads through the accessor instead of poking app.state directly. get_app_settings takes request and calls current_app_settings internally rather than declaring it as a sub-Depends — a Depends param typed with a TYPE_CHECKING-only forward ref makes FastAPI drop the marker and treat it as a query param.
This commit is contained in:
parent
4a3d045b85
commit
8b7f2664d0
2 changed files with 33 additions and 4 deletions
|
|
@ -5,7 +5,7 @@ from pathlib import Path
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
from cryptography.fernet import Fernet
|
from cryptography.fernet import Fernet
|
||||||
from fastapi import Request
|
from fastapi import FastAPI, HTTPException, Request, status
|
||||||
from pydantic import SecretStr
|
from pydantic import SecretStr
|
||||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
|
||||||
|
|
@ -27,6 +27,7 @@ class Settings(BaseSettings):
|
||||||
app_name: str = "Firebreak"
|
app_name: str = "Firebreak"
|
||||||
database_url: str = "postgresql+asyncpg://firebreak:firebreak@db:5432/firebreak_db"
|
database_url: str = "postgresql+asyncpg://firebreak:firebreak@db:5432/firebreak_db"
|
||||||
token_encryption_key: str = ""
|
token_encryption_key: str = ""
|
||||||
|
debug: bool = False
|
||||||
|
|
||||||
model_config = SettingsConfigDict(env_file=str(_env_file))
|
model_config = SettingsConfigDict(env_file=str(_env_file))
|
||||||
|
|
||||||
|
|
@ -56,6 +57,32 @@ def get_fernet() -> Fernet:
|
||||||
return fernet
|
return fernet
|
||||||
|
|
||||||
|
|
||||||
def get_app_settings(request: Request) -> AppSettings:
|
def current_app_settings(request: Request) -> AppSettings | None:
|
||||||
"""FastAPI dependency returning the AppSettings row from app state."""
|
"""Get AppSettings row, or None if not available.
|
||||||
|
|
||||||
|
This is the source of truth for the live AppSettings row
|
||||||
|
"""
|
||||||
return request.app.state.app_settings
|
return request.app.state.app_settings
|
||||||
|
|
||||||
|
|
||||||
|
def get_app_settings(request: Request) -> AppSettings:
|
||||||
|
"""FastAPI dependency that requires configured app settings.
|
||||||
|
|
||||||
|
Calls `current_app_settings` directly (rather than depending on it) so the
|
||||||
|
only injected parameter is the runtime-resolvable `request` — mirroring how
|
||||||
|
`get_current_session` calls `lookup_session`. Raises HTTP 500 when settings
|
||||||
|
are unavailable, which should only happen if a route that requires settings
|
||||||
|
is reached before setup completes (i.e. not gated by setup middleware).
|
||||||
|
"""
|
||||||
|
settings = current_app_settings(request)
|
||||||
|
if settings is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||||
|
detail="App settings unavailable — route not gated by setup middleware.",
|
||||||
|
)
|
||||||
|
return settings
|
||||||
|
|
||||||
|
|
||||||
|
def set_app_settings(app: FastAPI, row: AppSettings | None) -> None:
|
||||||
|
"""Set application settings on the FastAPI app state."""
|
||||||
|
app.state.app_settings = row
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,8 @@ from starlette.middleware.base import BaseHTTPMiddleware
|
||||||
from starlette.requests import Request
|
from starlette.requests import Request
|
||||||
from starlette.responses import RedirectResponse, Response
|
from starlette.responses import RedirectResponse, Response
|
||||||
|
|
||||||
|
from app.config import current_app_settings
|
||||||
|
|
||||||
|
|
||||||
class SetupRequiredMiddleware(BaseHTTPMiddleware):
|
class SetupRequiredMiddleware(BaseHTTPMiddleware):
|
||||||
"""Redirect all requests to /setup when the app has not been configured yet."""
|
"""Redirect all requests to /setup when the app has not been configured yet."""
|
||||||
|
|
@ -11,7 +13,7 @@ class SetupRequiredMiddleware(BaseHTTPMiddleware):
|
||||||
if path.startswith("/setup") or path.startswith("/static") or path == "/favicon.ico":
|
if path.startswith("/setup") or path.startswith("/static") or path == "/favicon.ico":
|
||||||
return await call_next(request)
|
return await call_next(request)
|
||||||
|
|
||||||
if request.app.state.app_settings is None:
|
if current_app_settings(request) is None:
|
||||||
if request.headers.get("HX-Request"):
|
if request.headers.get("HX-Request"):
|
||||||
response = Response(status_code=200)
|
response = Response(status_code=200)
|
||||||
response.headers["HX-Redirect"] = "/setup"
|
response.headers["HX-Redirect"] = "/setup"
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue