Files
lan-clipboard/backend/app/main.py
T
dbildhauerandClaude Opus 5.5 e9585b395c feat: admin-benutzerverwaltung und start-admin aus env
- GET/POST /api/admin/users, GET/PATCH/DELETE /api/admin/users/{id}
- Deaktivieren und Passwort-Reset beenden alle Sessions des Benutzers
- kein Ändern/Löschen des eigenen Accounts, letzter aktiver Admin geschützt
- INITIAL_ADMIN_USERNAME/PASSWORD legen den ersten Admin an, solange keine Benutzer existieren

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 11:04:33 +01:00

112 lines
3.7 KiB
Python

import asyncio
import logging
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from pathlib import Path
from fastapi import FastAPI, HTTPException, Request, status
from fastapi.concurrency import run_in_threadpool
from fastapi.responses import FileResponse, JSONResponse
from app import __version__
from app.api import admin, auth, health
from app.config import get_settings
from app.db import _session_factory
from app.middleware import OriginCheckMiddleware
from app.services.auth import delete_old_login_attempts
from app.services.sessions import delete_expired_sessions
from app.services.users import UserError, bootstrap_initial_admin
logger = logging.getLogger(__name__)
CLEANUP_INTERVAL_SECONDS = 3600
def _cleanup() -> None:
with _session_factory()() as db:
sessions = delete_expired_sessions(db)
attempts = delete_old_login_attempts(db)
if sessions or attempts:
logger.info("Cleanup: %d sessions, %d login attempts removed", sessions, attempts)
async def _cleanup_loop() -> None:
while True:
try:
await run_in_threadpool(_cleanup)
except Exception:
logger.exception("Cleanup failed")
await asyncio.sleep(CLEANUP_INTERVAL_SECONDS)
def _bootstrap_admin() -> None:
settings = get_settings()
if not (settings.initial_admin_username and settings.initial_admin_password):
return
with _session_factory()() as db:
try:
user = bootstrap_initial_admin(
db, settings.initial_admin_username, settings.initial_admin_password
)
except UserError as exc:
logger.error("INITIAL_ADMIN_* ignored: %s", exc)
return
if user is not None:
logger.warning(
"Initial admin '%s' created from INITIAL_ADMIN_*; remove these from .env now.",
user.username,
)
else:
logger.info("INITIAL_ADMIN_* ignored: users already exist; remove them from .env.")
@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
await run_in_threadpool(_bootstrap_admin)
task = asyncio.create_task(_cleanup_loop())
try:
yield
finally:
task.cancel()
def _register_frontend(app: FastAPI, static_dir: Path) -> None:
"""Serve the built Vue SPA; unknown non-API paths fall back to index.html."""
root = static_dir.resolve()
index_file = root / "index.html"
@app.get("/{path:path}", include_in_schema=False)
def spa(path: str) -> FileResponse:
if path == "api" or path.startswith("api/") or not index_file.is_file():
raise HTTPException(status_code=404)
candidate = (root / path).resolve()
if path and candidate.is_relative_to(root) and candidate.is_file():
return FileResponse(candidate)
return FileResponse(index_file, headers={"Cache-Control": "no-cache"})
def create_app() -> FastAPI:
settings = get_settings()
app = FastAPI(
title="LAN-Clipboard",
version=__version__,
docs_url="/api/docs",
openapi_url="/api/openapi.json",
redoc_url=None,
lifespan=lifespan,
)
app.add_middleware(OriginCheckMiddleware, allowed_origins=settings.allowed_origin_list)
app.include_router(health.router, prefix="/api")
app.include_router(auth.router, prefix="/api")
app.include_router(admin.router, prefix="/api")
@app.exception_handler(UserError)
def user_error_handler(_request: Request, exc: UserError) -> JSONResponse:
return JSONResponse({"detail": str(exc)}, status_code=status.HTTP_400_BAD_REQUEST)
_register_frontend(app, settings.static_dir)
return app
app = create_app()