From 2b0b19eb91d947b627e934809fd831c5a0c36c70 Mon Sep 17 00:00:00 2001 From: Garret Patti <42485635+garretpatti@users.noreply.github.com> Date: Mon, 29 Jun 2026 10:41:29 -0400 Subject: [PATCH] add auth --- .env.example | 16 +++ .gitea/workflows/container-publish.yml | 93 ++++++++++++++ AGENTS.md | 115 ++++++++++++++++-- .../alembic/versions/0002_add_users_table.py | 29 +++++ backend/app/auth.py | 81 ++++++++++++ backend/app/config.py | 19 +++ backend/app/main.py | 33 ++++- backend/app/models.py | 10 ++ backend/app/routers/auth.py | 76 ++++++++++++ backend/app/routers/libraries.py | 29 ++++- backend/app/routers/media.py | 28 ++++- backend/app/routers/search.py | 4 +- backend/app/routers/tags.py | 20 ++- backend/app/schemas.py | 25 ++++ backend/pyproject.toml | 2 + docker-compose.yml | 7 +- frontend/src/App.tsx | 69 +++++++++-- frontend/src/api/client.ts | 52 +++++++- frontend/src/auth/AuthContext.tsx | 86 +++++++++++++ frontend/src/auth/AuthTypes.ts | 19 +++ frontend/src/auth/useAuth.ts | 10 ++ frontend/src/pages/LoginPage.tsx | 100 +++++++++++++++ frontend/src/pages/SettingsPage.tsx | 90 +++++++++++++- 23 files changed, 969 insertions(+), 44 deletions(-) create mode 100644 .gitea/workflows/container-publish.yml create mode 100644 backend/alembic/versions/0002_add_users_table.py create mode 100644 backend/app/auth.py create mode 100644 backend/app/routers/auth.py create mode 100644 frontend/src/auth/AuthContext.tsx create mode 100644 frontend/src/auth/AuthTypes.ts create mode 100644 frontend/src/auth/useAuth.ts create mode 100644 frontend/src/pages/LoginPage.tsx diff --git a/.env.example b/.env.example index 0dc4deb..68b3cc5 100644 --- a/.env.example +++ b/.env.example @@ -2,3 +2,19 @@ # Library paths you configure in the app must be subdirectories of this path. # Inside the container, this maps to /media. MEDIA_ROOT=/mnt/nas + +# Authentication settings +# SECRET_KEY is used to sign JWT tokens. Leave unset to auto-generate one +# (all sessions will be invalidated on restart). +SECRET_KEY= + +# Admin user created on first startup. +ADMIN_USERNAME=admin +ADMIN_PASSWORD=change-me + +# JWT token expiry in days (default: 30). +ACCESS_TOKEN_EXPIRE_DAYS=30 + +# Gitea container registry owner (username or org). Used by docker-compose.yml +# to pull pre-built images. Defaults to "gpatti". +OWNER=gpatti diff --git a/.gitea/workflows/container-publish.yml b/.gitea/workflows/container-publish.yml new file mode 100644 index 0000000..e4e56e7 --- /dev/null +++ b/.gitea/workflows/container-publish.yml @@ -0,0 +1,93 @@ +name: Container Publish + +on: + push: + branches: [main] + tags: ["v*"] + workflow_dispatch: + +permissions: + contents: read + packages: write + +jobs: + backend: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Set up Docker Buildx + uses: https://github.com/docker/setup-buildx-action@v3 + + - name: Extract metadata + id: meta + run: | + REGISTRY=git.gpatti.com + OWNER="${{ gitea.repository_owner }}" + IMAGE_NAME="${REGISTRY}/${OWNER}/medialore-backend" + + echo "image=${IMAGE_NAME}" >> "$GITHUB_OUTPUT" + echo "registry=${REGISTRY}" >> "$GITHUB_OUTPUT" + + if [[ "${{ gitea.ref_type }}" == "tag" ]]; then + TAG="${{ gitea.ref_name }}" + VERSION="${TAG#v}" + echo "tags=${IMAGE_NAME}:${VERSION},${IMAGE_NAME}:latest" >> "$GITHUB_OUTPUT" + else + echo "tags=${IMAGE_NAME}:latest" >> "$GITHUB_OUTPUT" + fi + + - name: Log in to registry + run: | + echo "${{ secrets.REGISTRY_TOKEN }}" | \ + docker login "${{ steps.meta.outputs.registry }}" \ + -u "${{ secrets.REGISTRY_USER }}" \ + --password-stdin + + - name: Build and push + uses: https://github.com/docker/build-push-action@v6 + with: + context: ./backend + push: true + tags: ${{ steps.meta.outputs.tags }} + + frontend: + runs-on: ubuntu-latest + needs: [] + steps: + - uses: actions/checkout@v4 + + - name: Set up Docker Buildx + uses: https://github.com/docker/setup-buildx-action@v3 + + - name: Extract metadata + id: meta + run: | + REGISTRY=git.gpatti.com + OWNER="${{ gitea.repository_owner }}" + IMAGE_NAME="${REGISTRY}/${OWNER}/medialore-frontend" + + echo "image=${IMAGE_NAME}" >> "$GITHUB_OUTPUT" + echo "registry=${REGISTRY}" >> "$GITHUB_OUTPUT" + + if [[ "${{ gitea.ref_type }}" == "tag" ]]; then + TAG="${{ gitea.ref_name }}" + VERSION="${TAG#v}" + echo "tags=${IMAGE_NAME}:${VERSION},${IMAGE_NAME}:latest" >> "$GITHUB_OUTPUT" + else + echo "tags=${IMAGE_NAME}:latest" >> "$GITHUB_OUTPUT" + fi + + - name: Log in to registry + run: | + echo "${{ secrets.REGISTRY_TOKEN }}" | \ + docker login "${{ steps.meta.outputs.registry }}" \ + -u "${{ secrets.REGISTRY_USER }}" \ + --password-stdin + + - name: Build and push + uses: https://github.com/docker/build-push-action@v6 + with: + context: ./frontend + push: true + tags: ${{ steps.meta.outputs.tags }} diff --git a/AGENTS.md b/AGENTS.md index e1361d8..139fef5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,7 +2,7 @@ ## Project Overview -MediaLore is a **self-hosted media library browser** for images and videos. It provides a web UI for browsing, searching, tagging, and viewing media with thumbnail previews and doom-scroll/TikTok-style consumption. +MediaLore is a **self-hosted media library browser** for images and videos. It provides a web UI for browsing, searching, tagging, and viewing media with thumbnail previews and doom-scroll/TikTok-style consumption. **All access requires authentication** — users must log in before accessing any media or UI pages. **Monorepo** with two independent apps: - `backend/` — Python FastAPI server @@ -15,6 +15,7 @@ MediaLore is a **self-hosted media library browser** for images and videos. It p | Backend | Python 3.12+, FastAPI, Uvicorn | | Database | SQLite via SQLAlchemy (async aiosqlite), WAL mode | | Migrations | Alembic | +| Auth | JWT (python-jose) + bcrypt password hashing | | Thumbnails | Pillow (images), ffmpeg (videos) — generated on-demand | | File Watch | watchdog — live filesystem monitoring | | Frontend | React 19, TypeScript 6, Vite 8, React Router 7, TanStack Query v5 | @@ -25,7 +26,10 @@ MediaLore is a **self-hosted media library browser** for images and videos. It p ``` medialore-web-app/ ├── docker-compose.yml # Orchestration (backend, frontend, volumes) -├── .env.example # MEDIA_ROOT env var template +├── .env.example # Environment variable template +├── .gitea/ +│ └── workflows/ +│ └── container-publish.yml # CI: build & push Docker images ├── backend/ │ ├── Dockerfile │ ├── pyproject.toml # Python package config (hatchling build) @@ -35,11 +39,13 @@ medialore-web-app/ │ │ └── versions/ │ └── app/ │ ├── main.py # FastAPI app, CORS, lifespan, router registration -│ ├── config.py # Pydantic Settings (DATABASE_URL, MEDIA_ROOT, THUMBNAIL_DIR) +│ ├── config.py # Pydantic Settings (DATABASE_URL, MEDIA_ROOT, etc.) │ ├── database.py # SQLAlchemy async engine, session, WAL pragma -│ ├── models.py # ORM models: Library, MediaItem, Tag, media_item_tags -│ ├── schemas.py # Pydantic request/response schemas +│ ├── models.py # ORM models: Library, MediaItem, Tag, User, media_item_tags +│ ├── schemas.py # Pydantic request/response schemas (incl. auth) +│ ├── auth.py # bcrypt hashing, JWT create/decode, auth dependencies │ ├── routers/ +│ │ ├── auth.py # Login, token validation, user CRUD (admin) │ │ ├── libraries.py # Library CRUD, browse, doom-scroll, scan-status, rescan │ │ ├── media.py # Media item get, file serve, thumbnail, tag assignment │ │ ├── tags.py # Tag CRUD, grouped by category @@ -67,7 +73,12 @@ medialore-web-app/ ├── index.css # CSS custom properties for light/dark themes ├── api/ │ └── client.ts # Typed fetch wrapper; all endpoint functions + ├── auth/ + │ ├── AuthTypes.ts # AuthUser, AuthState interfaces, AuthContext + │ ├── AuthContext.tsx # AuthProvider component (login/logout/token mgmt) + │ └── useAuth.ts # useAuth hook ├── pages/ + │ ├── LoginPage.tsx │ ├── SearchPage.tsx │ ├── BrowserPage.tsx │ ├── SettingsPage.tsx @@ -126,11 +137,15 @@ docker compose up -d ## Environment Variables -| Variable | Default | Purpose | -|------------------|-------------------------------------|------------------------------| -| `DATABASE_URL` | `sqlite+aiosqlite:////data/medialore.db` | SQLite connection string | -| `MEDIA_ROOT` | `/media` | Root path for media libraries | -| `THUMBNAIL_DIR` | `/data/thumbnails` | Cached thumbnail storage | +| Variable | Default | Purpose | +|-------------------------|-------------------------------------|------------------------------| +| `DATABASE_URL` | `sqlite+aiosqlite:////data/medialore.db` | SQLite connection string | +| `MEDIA_ROOT` | `/media` | Root path for media libraries | +| `THUMBNAIL_DIR` | `/data/thumbnails` | Cached thumbnail storage | +| `SECRET_KEY` | auto-generated | JWT signing key | +| `ADMIN_USERNAME` | `admin` | Initial admin user | +| `ADMIN_PASSWORD` | (required) | Initial admin password | +| `ACCESS_TOKEN_EXPIRE_DAYS` | `30` | JWT token lifetime in days | Pydantic Settings reads from `.env` at startup (via `model_config = {"env_file": ".env"}`). For Docker, these are set in `docker-compose.yml`. @@ -144,13 +159,26 @@ SQLite with **WAL mode** and a 10-second busy timeout (see `app/database.py:14-1 - **media_items**: `id`, `library_id` (FK), `rel_path`, `filename`, `file_hash` (SHA-256), `media_type` ("image" or "video"), `size_bytes`, `missing`, `created_at`, `updated_at` — unique on `(library_id, rel_path)` - **tags**: `id`, `name`, `category` — unique on `(name, category)` - **media_item_tags**: `media_item_id` (FK), `tag_id` (FK), composite PK +- **users**: `id`, `username` (unique), `password_hash`, `is_admin`, `created_at` -**Migrations**: Use Alembic. The initial migration is at `backend/alembic/versions/0001_initial_schema.py`. +**Migrations**: Use Alembic. The initial migration is at `backend/alembic/versions/0001_initial_schema.py` and the users table migration at `0002_add_users_table.py`. ## API Conventions All endpoints are prefixed with `/api`. All responses are JSON except `/api/media/:id/file` (binary stream) and `/api/media/:id/thumbnail` (JPEG). +**All endpoints require authentication** except `POST /api/auth/login`. The `Authorization: Bearer ` header must be included. File and thumbnail endpoints also accept `?token=` as a query parameter (for ``/`