Add first-run setup wizard and file browser for library creation

- On first start (no users in DB), show a setup page in the web UI
  to create the admin account instead of reading credentials from .env
- New public endpoints: GET /api/setup/status, POST /api/setup
- New admin endpoint: GET /api/filebrowser?path=... for directory listing
- FileBrowser modal component with navigation, used in Admin > Libraries
- Remove _seed_admin / _seed_default_library from server startup

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Audiolib
2026-05-26 13:30:42 +02:00
parent adbe3c2507
commit afba751c21
7 changed files with 309 additions and 59 deletions

View File

@@ -1,4 +1,3 @@
import uuid
import logging
import os
from contextlib import asynccontextmanager
@@ -7,13 +6,10 @@ from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from .database import init_db, AsyncSessionLocal
from .database import init_db
from .config import get_settings
from .models import User, Library
from .services.auth import hash_password, verify_password, create_token
from .services.file_watcher import start_file_watcher, stop_file_watcher
from .services.podcast_feed import update_all_feeds
from sqlalchemy import select
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
logger = logging.getLogger(__name__)
@@ -21,50 +17,6 @@ logger = logging.getLogger(__name__)
_scheduler = AsyncIOScheduler()
async def _seed_admin():
settings = get_settings()
async with AsyncSessionLocal() as db:
result = await db.execute(select(User).where(User.is_admin == True))
existing = result.scalar_one_or_none()
if existing:
if not verify_password(settings.admin_password, existing.password_hash):
existing.password_hash = hash_password(settings.admin_password)
await db.commit()
logger.info("Admin-Passwort aus ENV aktualisiert.")
return
logger.info(f"Lege Admin-User an: {settings.admin_username}")
admin = User(
id=str(uuid.uuid4()),
username=settings.admin_username,
email=settings.admin_email,
password_hash=hash_password(settings.admin_password),
is_admin=True,
)
db.add(admin)
await db.flush()
admin.token = create_token(admin.id)
await db.commit()
logger.info("Admin-User angelegt.")
async def _seed_default_library():
settings = get_settings()
async with AsyncSessionLocal() as db:
result = await db.execute(select(Library))
if result.scalar_one_or_none():
return
folder_id = str(uuid.uuid4())
lib = Library(
id=str(uuid.uuid4()),
name="Hörbücher",
display_name="Hörbücher",
folders=[{"id": folder_id, "fullPath": settings.audiofiles_path}],
media_type="book",
settings={"icon": "headphones", "provider": "google"},
)
db.add(lib)
await db.commit()
logger.info(f"Standard-Library angelegt: {settings.audiofiles_path}")
@asynccontextmanager
@@ -74,8 +26,6 @@ async def lifespan(app: FastAPI):
os.makedirs(d, exist_ok=True)
await init_db()
await _seed_admin()
await _seed_default_library()
await start_file_watcher()
# Podcast-Feed-Scheduler
@@ -105,8 +55,9 @@ if os.path.exists(settings.covers_dir):
app.mount("/covers", StaticFiles(directory=settings.covers_dir), name="covers")
from .routers import auth, libraries, items, stream, me, users, settings as settings_router
from .routers import matching, podcasts
from .routers import matching, podcasts, setup, filebrowser
app.include_router(setup.router)
app.include_router(auth.router)
app.include_router(libraries.router)
app.include_router(items.router)
@@ -116,3 +67,4 @@ app.include_router(users.router)
app.include_router(settings_router.router)
app.include_router(matching.router)
app.include_router(podcasts.router)
app.include_router(filebrowser.router)

View File

@@ -0,0 +1,37 @@
import os
from fastapi import APIRouter, Depends, HTTPException, Query
from ..dependencies import require_admin
from ..models.user import User
router = APIRouter(prefix="/api/filebrowser", tags=["filebrowser"])
@router.get("")
async def browse(
path: str = Query("/"),
_admin: User = Depends(require_admin),
):
path = os.path.normpath(path)
if not os.path.isdir(path):
raise HTTPException(status_code=404, detail="Pfad nicht gefunden")
try:
names = sorted(os.listdir(path), key=lambda n: n.lower())
except PermissionError:
raise HTTPException(status_code=403, detail="Zugriff verweigert")
entries = []
for name in names:
if name.startswith("."):
continue
full = os.path.join(path, name)
try:
is_dir = os.path.isdir(full)
except OSError:
continue
entries.append({"name": name, "path": full, "isDir": is_dir})
parent_path = os.path.dirname(path)
parent = parent_path if parent_path != path else None
return {"path": path, "parent": parent, "entries": entries}

View File

@@ -0,0 +1,43 @@
import uuid
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func
from pydantic import BaseModel
from ..dependencies import get_db
from ..models.user import User
from ..services.auth import hash_password, create_token
router = APIRouter(prefix="/api/setup", tags=["setup"])
class SetupRequest(BaseModel):
username: str
password: str
email: str = ""
@router.get("/status")
async def setup_status(db: AsyncSession = Depends(get_db)):
result = await db.execute(select(func.count()).select_from(User))
count = result.scalar()
return {"needsSetup": count == 0}
@router.post("")
async def run_setup(body: SetupRequest, db: AsyncSession = Depends(get_db)):
result = await db.execute(select(func.count()).select_from(User))
if result.scalar() > 0:
raise HTTPException(status_code=400, detail="Setup already completed")
admin = User(
id=str(uuid.uuid4()),
username=body.username,
email=body.email,
password_hash=hash_password(body.password),
is_admin=True,
)
db.add(admin)
await db.flush()
admin.token = create_token(admin.id)
await db.commit()
return {"success": True}