from __future__ import annotations import logging from contextlib import asynccontextmanager from fastapi import FastAPI from .. import __version__ from ..config import get_settings from ..logging_setup import configure_logging from .routes import ( auth, captures, commands, conditions, device_config, enroll, firmware, health, ingest, ) from .userauth import csrf_middleware log = logging.getLogger(__name__) API_PREFIX = "/api/v1" @asynccontextmanager async def lifespan(app: FastAPI): settings = get_settings() log.info( "poorbird api starting", extra={"version": __version__, "image_root": str(settings.image_root)}, ) if not settings.enroll_secret_is_set: # A warning rather than a refusal to start: an existing camera keeps # working with the token it already holds, and taking the whole API # down would also take down the gallery. Only enrollment breaks. log.warning("POORBIRD_ENROLL_SECRET is not set; device enrollment will refuse requests") yield log.info("poorbird api stopping") def create_app() -> FastAPI: settings = get_settings() configure_logging(settings.log_level, settings.log_format) app = FastAPI( title="poorBird", version=__version__, summary="Ingest, gallery and device management for a radar-triggered bird camera", lifespan=lifespan, ) # CSRF for cookie-authenticated mutations. Middleware rather than a # per-route dependency so a new endpoint cannot forget it; it applies only # to unsafe methods on requests that carry the session cookie, which is why # the device endpoints -- bearer tokens, no cookies -- are unaffected. See # userauth.csrf_middleware. app.middleware("http")(csrf_middleware) app.include_router(health.router, prefix=API_PREFIX, tags=["health"]) app.include_router(health.root_router) # Phase 3 WebUI endpoints. app.include_router(auth.router, prefix=API_PREFIX) app.include_router(captures.router, prefix=API_PREFIX) # Phase 2 device endpoints. See firmware/API.md for the contract. app.include_router(enroll.router, prefix=API_PREFIX) app.include_router(conditions.router, prefix=API_PREFIX) app.include_router(device_config.router, prefix=API_PREFIX) app.include_router(commands.router, prefix=API_PREFIX) app.include_router(ingest.router, prefix=API_PREFIX) app.include_router(firmware.router, prefix=API_PREFIX) # The device contract (firmware/API.md) is complete apart from /stream, # which is Phase 6. Still to come on the operator side: the admin-facing # POST /firmware and device management, both Phase 4. return app app = create_app()