diff --git a/app/auth.py b/app/auth.py index 6cb8cd7..fc3ca8f 100644 --- a/app/auth.py +++ b/app/auth.py @@ -102,3 +102,9 @@ def current_user( if user_id is None: raise HTTPException(status_code=401, detail="Non authentifié") return user_id + + +def get_username(user_id: int) -> str | None: + with SessionLocal() as db: + user = db.get(User, user_id) + return user.username if user else None diff --git a/app/main.py b/app/main.py index 7dfe2a1..a93486b 100644 --- a/app/main.py +++ b/app/main.py @@ -2,21 +2,26 @@ import os import shutil from contextlib import asynccontextmanager from datetime import UTC, datetime +from pathlib import Path from typing import Annotated import httpx -from fastapi import Depends, FastAPI, HTTPException +from fastapi import Cookie, Depends, FastAPI, HTTPException, Response from fastapi.middleware.cors import CORSMiddleware -from fastapi.staticfiles import StaticFiles +from fastapi.responses import FileResponse from sqlalchemy import inspect, select, text from sqlalchemy.orm import Session +from app import auth from app.conf_store import read_config, write_config from app.database import Base, engine, get_db from app.models import IsoMovie from app.radarr import RadarrClient, movie_file_path from app.schemas import ( ApiServiceSettingsRead, + AuthCredentialsWrite, + AuthSetupWrite, + AuthUserRead, ConnectionResult, HealthRead, IsoMovieRead, @@ -44,6 +49,7 @@ async def lifespan(_: FastAPI): except Exception: # Don't fail app startup for a best-effort migration. pass + auth.bootstrap_setup() yield @@ -235,10 +241,65 @@ async def scan_radarr(db: DbSession) -> ScanResult: ) -# Service du front : monte web/dist en racine quand l'image le fournit -# (MKVTOOL_WEB_DIR). Le montage est declare en dernier, donc les routes /api -# ci-dessus gardent la priorite; en dev (vite sur :5173), la variable est -# absente et le montage est saute. +# --- Authentification locale --- +# Premier lancement: le lien affiche dans les logs par bootstrap_setup() porte +# un jeton a usage unique; il disparait des qu'un compte existe. +@app.post("/api/auth/setup", response_model=AuthUserRead) +def auth_setup(payload: AuthSetupWrite, response: Response) -> AuthUserRead: + if auth.setup_token is None or payload.token != auth.setup_token: + raise HTTPException(status_code=403, detail="Lien de création invalide ou expiré") + if auth.user_count() > 0: + raise HTTPException(status_code=403, detail="Un compte existe déjà") + user_id = auth.create_user(payload.username, payload.password) + auth.setup_token = None + response.set_cookie( + auth.SESSION_COOKIE, auth.create_session(user_id), httponly=True, samesite="lax" + ) + return AuthUserRead(username=payload.username) + + +@app.post("/api/auth/login", response_model=AuthUserRead) +def auth_login(payload: AuthCredentialsWrite, response: Response) -> AuthUserRead: + user_id = auth.check_credentials(payload.username, payload.password) + if user_id is None: + raise HTTPException(status_code=401, detail="Identifiants incorrects") + response.set_cookie( + auth.SESSION_COOKIE, auth.create_session(user_id), httponly=True, samesite="lax" + ) + return AuthUserRead(username=payload.username) + + +@app.get("/api/auth/me", response_model=AuthUserRead) +def auth_me(user_id: int = Depends(auth.current_user)) -> AuthUserRead: + username = auth.get_username(user_id) + if username is None: + raise HTTPException(status_code=401, detail="Non authentifié") + return AuthUserRead(username=username) + + +@app.post("/api/auth/logout") +def auth_logout( + response: Response, + mkvtool_session: str | None = Cookie(default=None, alias=auth.SESSION_COOKIE), +) -> dict[str, bool]: + auth.end_session(mkvtool_session) + response.delete_cookie(auth.SESSION_COOKIE) + return {"ok": True} + + +# Service du front : sert web/dist (fourni par l'image via MKVTOOL_WEB_DIR). +# Le catch-all est declare en dernier, donc les routes /api ci-dessus gardent la +# priorite; les chemins inconnus (ex: /setup?token=...) renvoient le SPA pour +# son routage cote client. En dev (vite sur :5173), la variable est absente. web_dir = os.environ.get("MKVTOOL_WEB_DIR") if web_dir and os.path.isdir(web_dir): - app.mount("/", StaticFiles(directory=web_dir, html=True), name="web") + + @app.get("/{full_path:path}", include_in_schema=False) + async def serve_web(full_path: str) -> FileResponse: + if full_path.startswith("api/"): + raise HTTPException(status_code=404, detail="Route inconnue") + root = Path(web_dir).resolve() + candidate = (root / full_path).resolve() + if full_path and candidate.is_file() and candidate.is_relative_to(root): + return FileResponse(candidate) + return FileResponse(root / "index.html") diff --git a/app/models.py b/app/models.py index 2c914cc..17aa440 100644 --- a/app/models.py +++ b/app/models.py @@ -30,3 +30,12 @@ class IsoMovie(Base): ) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) processed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) + + +class User(Base): + __tablename__ = "users" + + id: Mapped[int] = mapped_column(primary_key=True) + username: Mapped[str] = mapped_column(String(100), unique=True) + password_hash: Mapped[str] = mapped_column(String(255)) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) diff --git a/app/schemas.py b/app/schemas.py index 7d90d2e..dd95f3e 100644 --- a/app/schemas.py +++ b/app/schemas.py @@ -87,3 +87,18 @@ class HealthRead(BaseModel): database: str makemkv_available: bool makemkv_version: str | None + + +class AuthSetupWrite(BaseModel): + token: str + username: str + password: str + + +class AuthCredentialsWrite(BaseModel): + username: str + password: str + + +class AuthUserRead(BaseModel): + username: str