Compare commits

..
3 Commits
5 changed files with 188 additions and 1 deletions

No files matched your search

+6
View File
@@ -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
+120 -1
View File
@@ -2,24 +2,32 @@ 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.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.qbittorrent import QbittorrentClient
from app.radarr import RadarrClient, movie_file_path
from app.schemas import (
ApiServiceSettingsRead,
AuthCredentialsWrite,
AuthSetupWrite,
AuthUserRead,
ConnectionResult,
HealthRead,
IsoMovieRead,
QbittorrentSettingsRead,
QbittorrentSettingsWrite,
RadarrSettingsRead,
RadarrSettingsWrite,
ScanResult,
@@ -43,6 +51,7 @@ async def lifespan(_: FastAPI):
except Exception:
# Don't fail app startup for a best-effort migration.
pass
auth.bootstrap_setup()
yield
@@ -165,6 +174,52 @@ async def test_radarr() -> ConnectionResult:
return ConnectionResult(success=True, version=version, message=f"Radarr {version} accessible")
def qbittorrent_from_config() -> QbittorrentClient:
qb = read_config().qbittorrent
if not qb.url or not qb.username or not qb.password:
raise HTTPException(status_code=409, detail="La connexion qBittorrent n'est pas configurée")
return QbittorrentClient(qb.url, qb.username, qb.password)
@app.get("/api/settings/qbittorrent", response_model=QbittorrentSettingsRead)
def get_qbittorrent_settings() -> QbittorrentSettingsRead:
qb = read_config().qbittorrent
return QbittorrentSettingsRead(
url=qb.url, username=qb.username, password_configured=qb.password is not None
)
@app.put("/api/settings/qbittorrent", response_model=QbittorrentSettingsRead)
def put_qbittorrent_settings(payload: QbittorrentSettingsWrite) -> QbittorrentSettingsRead:
cfg = read_config()
if payload.url is not None:
cfg.qbittorrent.url = str(payload.url).rstrip("/")
if payload.username:
cfg.qbittorrent.username = payload.username
if payload.password:
cfg.qbittorrent.password = payload.password
write_config(cfg)
return QbittorrentSettingsRead(
url=cfg.qbittorrent.url,
username=cfg.qbittorrent.username,
password_configured=cfg.qbittorrent.password is not None,
)
@app.post("/api/settings/qbittorrent/test", response_model=ConnectionResult)
async def test_qbittorrent() -> ConnectionResult:
client = qbittorrent_from_config()
try:
version = await client.version()
except (httpx.HTTPError, ValueError) as error:
raise HTTPException(
status_code=502, detail=f"Connexion qBittorrent impossible: {error}"
) from error
return ConnectionResult(
success=True, version=version, message=f"qBittorrent {version} accessible"
)
@app.get("/api/movies", response_model=list[IsoMovieRead])
def list_movies(db: DbSession) -> list[IsoMovie]:
return list(db.scalars(select(IsoMovie).order_by(IsoMovie.title)).all())
@@ -232,3 +287,67 @@ async def scan_radarr(db: DbSession) -> ScanResult:
return ScanResult(
scanned_movies=len(movies), iso_files=iso_files, created=created, updated=updated
)
# --- 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.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())
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
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
+38
View File
@@ -1,7 +1,10 @@
import json
import respx
from fastapi.testclient import TestClient
from httpx import Response
from app.conf_store import config_path
from app.main import app
@@ -70,3 +73,38 @@ def test_scan_only_imports_iso_files() -> None:
assert scan.status_code == 200
assert scan.json()["iso_files"] == 1
assert [movie["title"] for movie in movies.json()] == ["ISO Movie"]
@respx.mock
def test_qbittorrent_connection() -> None:
respx.post("http://qbit:8080/api/v2/auth/login").mock(
return_value=Response(200, text="Ok.")
)
respx.get("http://qbit:8080/api/v2/app/version").mock(
return_value=Response(200, text="v5.0.2")
)
with TestClient(app) as client:
response = client.put(
"/api/settings/qbittorrent",
json={"url": "http://qbit:8080", "username": "admin", "password": "pass"},
)
assert response.status_code == 200
test = client.post("/api/settings/qbittorrent/test")
assert test.status_code == 200
assert test.json()["version"] == "v5.0.2"
def test_settings_persist_to_conf_json() -> None:
with TestClient(app) as client:
put = client.put(
"/api/settings/qbittorrent",
json={"url": "http://qbit:8080/", "username": "admin", "password": "pass"},
)
got = client.get("/api/settings/qbittorrent")
assert put.status_code == 200
assert put.json()["password_configured"] is True
assert got.json()["url"] == "http://qbit:8080"
raw = json.loads(config_path().read_text(encoding="utf-8"))
assert raw["qbittorrent"]["url"] == "http://qbit:8080"
assert raw["qbittorrent"]["username"] == "admin"
assert raw["qbittorrent"]["password"] == "pass"