from fastapi import Depends, FastAPI from fastapi.middleware.cors import CORSMiddleware from sqlalchemy import text from .auth import require_api_key from .config import get_settings from .database import engine from .errors import APIError, api_error_handler from .routers import ( customers, device, nas, nasreload, radacct, radcheck, radgroupcheck, radgroupreply, radpostauth, radreply, radusergroup, vlan, ) settings = get_settings() app = FastAPI( title="FreeRADIUS REST API", description="RESTful CRUD over the FreeRADIUS SQL schema. " "All endpoints require the `X-API-Key` header.", version="1.0.0", ) app.add_middleware( CORSMiddleware, allow_origins=settings.cors_origin_list, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.add_exception_handler(APIError, api_error_handler) # ---- unauthenticated meta endpoints ---- @app.get("/", tags=["meta"]) def root(): return {"service": "freeradius-rest-api", "docs": "/docs", "health": "/health"} @app.get("/health", tags=["meta"]) def health(): try: with engine.connect() as conn: conn.execute(text("SELECT 1")) db_ok = True except Exception: db_ok = False return {"status": "ok" if db_ok else "degraded", "database": "up" if db_ok else "down"} # ---- authenticated resource routers ---- protected = [Depends(require_api_key)] for module in ( customers, nas, radcheck, radreply, radgroupcheck, radgroupreply, radusergroup, vlan, device, radacct, radpostauth, nasreload, ): app.include_router(module.router, dependencies=protected)