Initial commit with webpage

This commit is contained in:
bkelldog committed 2026-11-06 11:42:34 -05:00
commit 26875de1dd
55 files changed
+5726

No files matched your search

+162
View File
@@ -0,0 +1,162 @@
"""The web app: device API + dashboard + JSON API in one process.
Run locally: uvicorn app.main:app --reload
API docs: http://localhost:8000/docs
"""
import logging
from contextlib import asynccontextmanager
from urllib.parse import urlsplit
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, PlainTextResponse, RedirectResponse, Response
from fastapi.staticfiles import StaticFiles
from sqlalchemy import text
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.middleware.sessions import SessionMiddleware
from . import __version__
from .config import DEV_SECRET, WEB_DIR, get_settings
from .db import SessionLocal, engine
from .routes import admin, api, auth, device_api, pages
from .services.catalog import ensure_defaults
from .web import APP_DIR, LoginRequired, render
log = logging.getLogger("mamadachi")
def run_migrations() -> None:
"""Bring the database schema up to date (same as `alembic upgrade head`)."""
from alembic import command
from alembic.config import Config
cfg = Config(str(WEB_DIR / "alembic.ini"))
cfg.set_main_option("script_location", str(WEB_DIR / "migrations"))
command.upgrade(cfg, "head")
@asynccontextmanager
async def lifespan(_app: FastAPI): # noqa: ANN201
settings = get_settings()
logging.basicConfig(level=settings.log_level, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
if settings.is_production:
# Fail loudly at deploy time rather than quietly losing data later.
if settings.is_sqlite and not settings.allow_sqlite_in_production:
raise RuntimeError(
"DATABASE_URL is not set, so the app would store data in a SQLite file that this host "
"deletes on every deploy. Set DATABASE_URL to your Postgres connection string."
)
if settings.login_required and settings.secret_key == DEV_SECRET:
raise RuntimeError("Set SECRET_KEY to a long random string, or anyone could forge a login cookie.")
if not settings.login_required:
log.error("DASHBOARD_PASSWORD is not set: anyone with the URL can see the dashboard.")
if settings.auto_migrate:
run_migrations()
with SessionLocal() as db:
ensure_defaults(db)
log.info("Mamadachi %s ready (%s)", __version__, engine.url.render_as_string(hide_password=True))
yield
settings = get_settings()
app = FastAPI(
title="Mamadachi",
version=__version__,
summary="Baby-event tracker: device sync API, dashboard API and website.",
lifespan=lifespan,
)
@app.middleware("http")
async def same_origin_and_headers(request: Request, call_next): # noqa: ANN001, ANN201
# Block cross-site form posts (CSRF). Browsers send Origin on POST; the
# device doesn't, and it authenticates with its token anyway.
if request.method not in ("GET", "HEAD", "OPTIONS"):
origin = request.headers.get("origin")
if origin and origin != "null" and urlsplit(origin).netloc != request.headers.get("host"):
return PlainTextResponse("Cross-site request blocked.", status_code=403)
response: Response = await call_next(request)
response.headers.setdefault("X-Content-Type-Options", "nosniff")
response.headers.setdefault("Referrer-Policy", "same-origin")
response.headers.setdefault("X-Frame-Options", "DENY")
return response
app.add_middleware(
SessionMiddleware,
secret_key=settings.secret_key,
session_cookie="mamadachi",
max_age=60 * 60 * 24 * 90, # stay logged in for 90 days on the parent's phone
same_site="lax",
https_only=settings.is_production,
)
app.mount("/static", StaticFiles(directory=APP_DIR / "static"), name="static")
@app.exception_handler(LoginRequired)
async def _login_redirect(request: Request, _exc: LoginRequired) -> RedirectResponse:
target = request.url.path + (f"?{request.url.query}" if request.url.query else "")
return RedirectResponse(f"/login?next={target}", status_code=303)
def _wants_html(request: Request) -> bool:
return not request.url.path.startswith("/api/") and "text/html" in request.headers.get("accept", "")
@app.exception_handler(StarletteHTTPException)
async def _http_error(request: Request, exc: StarletteHTTPException) -> Response:
if _wants_html(request):
with SessionLocal() as db:
return render(request, db, "error.html", status_code=exc.status_code, code=exc.status_code, detail=exc.detail)
return JSONResponse({"detail": exc.detail}, status_code=exc.status_code, headers=getattr(exc, "headers", None))
@app.exception_handler(RequestValidationError)
async def _validation_error(request: Request, exc: RequestValidationError) -> JSONResponse:
# Log what the device sent wrong: invaluable while writing firmware.
log.warning("422 on %s: %s", request.url.path, exc.errors()[:3])
return JSONResponse({"detail": exc.errors()}, status_code=422)
@app.get("/healthz", include_in_schema=False)
def healthz() -> dict:
"""Liveness: the process is up. Used by the host's health checks."""
return {"ok": True, "version": __version__}
@app.get("/readyz", include_in_schema=False)
def readyz() -> JSONResponse:
"""Readiness: the database answers too."""
try:
with engine.connect() as conn:
conn.execute(text("SELECT 1"))
except Exception as e: # noqa: BLE001
log.error("database check failed: %s", e)
return JSONResponse({"ok": False, "database": "unreachable"}, status_code=503)
return JSONResponse({"ok": True, "database": "ok"})
@app.get("/manifest.webmanifest", include_in_schema=False)
def manifest() -> JSONResponse:
"""Lets the parent "Add to Home Screen" and open the dashboard like an app."""
return JSONResponse(
{
"name": "Mamadachi",
"short_name": "Mamadachi",
"start_url": "/",
"display": "standalone",
"background_color": "#f9f9f7",
"theme_color": "#f9f9f7",
"icons": [{"src": "/static/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any"}],
},
media_type="application/manifest+json",
)
app.include_router(device_api.router)
app.include_router(api.router)
app.include_router(auth.router)
app.include_router(pages.router)
app.include_router(admin.router)