✨ Auth: routes /api/auth/*, modele User, lien de setup affiche au premier lancement + fallback SPA

This commit is contained in:
Orionis312050 committed 2026-10-11 16:30:46 +00:00
1 parent c19bc48318
commit de4a9b212f
4 files changed
+98 -7

No files matched your search

+6
View File
@@ -102,3 +102,9 @@ def current_user(
if user_id is None: if user_id is None:
raise HTTPException(status_code=401, detail="Non authentifié") raise HTTPException(status_code=401, detail="Non authentifié")
return user_id 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
+68 -7
View File
@@ -2,21 +2,26 @@ import os
import shutil import shutil
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
from datetime import UTC, datetime from datetime import UTC, datetime
from pathlib import Path
from typing import Annotated from typing import Annotated
import httpx import httpx
from fastapi import Depends, FastAPI, HTTPException from fastapi import Cookie, Depends, FastAPI, HTTPException, Response
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles from fastapi.responses import FileResponse
from sqlalchemy import inspect, select, text from sqlalchemy import inspect, select, text
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from app import auth
from app.conf_store import read_config, write_config from app.conf_store import read_config, write_config
from app.database import Base, engine, get_db from app.database import Base, engine, get_db
from app.models import IsoMovie from app.models import IsoMovie
from app.radarr import RadarrClient, movie_file_path from app.radarr import RadarrClient, movie_file_path
from app.schemas import ( from app.schemas import (
ApiServiceSettingsRead, ApiServiceSettingsRead,
AuthCredentialsWrite,
AuthSetupWrite,
AuthUserRead,
ConnectionResult, ConnectionResult,
HealthRead, HealthRead,
IsoMovieRead, IsoMovieRead,
@@ -44,6 +49,7 @@ async def lifespan(_: FastAPI):
except Exception: except Exception:
# Don't fail app startup for a best-effort migration. # Don't fail app startup for a best-effort migration.
pass pass
auth.bootstrap_setup()
yield 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 # --- Authentification locale ---
# (MKVTOOL_WEB_DIR). Le montage est declare en dernier, donc les routes /api # Premier lancement: le lien affiche dans les logs par bootstrap_setup() porte
# ci-dessus gardent la priorite; en dev (vite sur :5173), la variable est # un jeton a usage unique; il disparait des qu'un compte existe.
# absente et le montage est saute. @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") web_dir = os.environ.get("MKVTOOL_WEB_DIR")
if web_dir and os.path.isdir(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")
+9
View File
@@ -30,3 +30,12 @@ class IsoMovie(Base):
) )
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) 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) 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())
+15
View File
@@ -87,3 +87,18 @@ class HealthRead(BaseModel):
database: str database: str
makemkv_available: bool makemkv_available: bool
makemkv_version: str | None 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