add auth
This commit is contained in:
115
AGENTS.md
115
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 <token>` header must be included. File and thumbnail endpoints also accept `?token=` as a query parameter (for `<img>`/`<video>` tags that can't send headers).
|
||||
|
||||
### Auth Endpoints
|
||||
|
||||
| Method | Path | Auth | Purpose |
|
||||
|--------|-------------------|--------|-----------------------------|
|
||||
| `POST` | `/auth/login` | Public | Returns JWT `access_token` |
|
||||
| `GET` | `/auth/me` | User | Current user info |
|
||||
| `GET` | `/auth/users` | Admin | List all users |
|
||||
| `POST` | `/auth/users` | Admin | Create a new user |
|
||||
| `DELETE` | `/auth/users/{id}` | Admin | Delete a user (not self) |
|
||||
|
||||
### Async Database Access
|
||||
|
||||
Routers use FastAPI's `Depends` injection with the `get_db` async generator from `database.py`:
|
||||
@@ -163,6 +191,37 @@ async def endpoint(db: AsyncSession = Depends(get_db)):
|
||||
...
|
||||
```
|
||||
|
||||
### Authentication Dependency
|
||||
|
||||
All protected endpoints use `get_current_user` (from `app/auth.py`) as a FastAPI dependency:
|
||||
|
||||
```python
|
||||
from app.auth import get_current_user
|
||||
from app.models import User
|
||||
|
||||
@router.get("/...")
|
||||
async def endpoint(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_user: User = Depends(get_current_user),
|
||||
):
|
||||
...
|
||||
```
|
||||
|
||||
Admin-only endpoints chain `get_current_admin_user`:
|
||||
|
||||
```python
|
||||
from app.auth import get_current_admin_user
|
||||
|
||||
@router.delete("/users/{user_id}")
|
||||
async def delete_user(
|
||||
user_id: int,
|
||||
current_user: User = Depends(get_current_admin_user),
|
||||
...
|
||||
):
|
||||
```
|
||||
|
||||
File and thumbnail endpoints use `get_current_user_from_query_or_header` which accepts the token via `Authorization` header or `?token=` query parameter.
|
||||
|
||||
### Frontend API Client
|
||||
|
||||
All API calls go through the typed `api` object in `frontend/src/api/client.ts`. Use `useQuery` / `useMutation` from TanStack Query. Never call `fetch` directly from components.
|
||||
@@ -186,6 +245,8 @@ const { data } = useQuery({
|
||||
- Service modules handle business logic; routers handle HTTP concerns
|
||||
- Background scanning runs via `asyncio.create_task`; watchers run in separate threads via `watchdog.Observer`
|
||||
- Logging: use `logging.getLogger(__name__)` — the `app` namespace has a StreamHandler configured in `main.py`
|
||||
- Auth: use `bcrypt` directly (not passlib) for password hashing; `python-jose` for JWT tokens
|
||||
- All protected endpoints must include `_user: User = Depends(get_current_user)` as a parameter
|
||||
|
||||
### Frontend (TypeScript/React)
|
||||
- **ESLint flat config** with strict TypeScript-ESLint rules
|
||||
@@ -193,8 +254,10 @@ const { data } = useQuery({
|
||||
- TypeScript interfaces for all API types live in `client.ts`
|
||||
- Components use `useState`/`useEffect`/`useQuery` hooks, not class components
|
||||
- Theme state persisted in `localStorage` key `"theme"`, applied as `data-theme` attribute
|
||||
- Auth token persisted in `localStorage` key `"token"`, managed via `AuthProvider` context
|
||||
- Responsive via `window.matchMedia("(max-width: 767px)")` listener
|
||||
- File/thumbnail URLs constructed with `api.media.fileUrl(id)` and `api.media.thumbnailUrl(id)` (not fetched)
|
||||
- API client automatically injects `Authorization: Bearer <token>` header; handles 401 by clearing token
|
||||
|
||||
### TypeScript Configuration
|
||||
- `tsconfig.app.json`: strict mode, `noUnusedLocals`, `noUnusedParameters`, `erasableSyntaxOnly`
|
||||
@@ -211,16 +274,42 @@ const { data } = useQuery({
|
||||
## Docker / Deployment
|
||||
|
||||
- `docker compose up -d` starts both services
|
||||
- Backend runs on port 8000 (internal), frontend Nginx on port 80 (mapped to 8085 on host)
|
||||
- Images are pulled from the Gitea container registry (`git.gpatti.com/<owner>/medialore-backend` and `...frontend`)
|
||||
- Backend runs on port 8000 (internal), frontend Nginx on port 80 (mapped to 8080 on host)
|
||||
- Nginx proxies `/api/` to `http://backend:8000`
|
||||
- Media paths from the host are volume-mounted into the container at `/media`
|
||||
- Persistent data (DB, thumbnails) stored in Docker volume `medialore-data`
|
||||
- Set `OWNER` in `.env` to control which registry namespace images are pulled from
|
||||
|
||||
### CI/CD (Gitea Actions)
|
||||
|
||||
The workflow at `.gitea/workflows/container-publish.yml` automatically builds and pushes Docker images to the Gitea container registry on push to `main` or version tags (`v*`).
|
||||
|
||||
**Required secrets** (set in repo Settings → Actions → Secrets):
|
||||
| Secret | Purpose |
|
||||
|--------|---------|
|
||||
| `REGISTRY_USER` | Gitea username for docker login |
|
||||
| `REGISTRY_TOKEN` | Gitea PAT with `read:packages` and `write:packages` scopes |
|
||||
|
||||
To pull images from the private registry on a host, run `docker login git.gpatti.com` first with the same credentials.
|
||||
|
||||
### Local Development (without registry)
|
||||
|
||||
For local development without pulling from the registry, switch docker-compose.yml back to local builds:
|
||||
```yaml
|
||||
services:
|
||||
backend:
|
||||
build: ./backend # instead of image: ...
|
||||
frontend:
|
||||
build: ./frontend # instead of image: ...
|
||||
```
|
||||
|
||||
## Important Notes
|
||||
|
||||
- **No auth/authentication** — CORS allows all origins, no login system
|
||||
- **Authentication is required** for all endpoints and UI pages except `/api/auth/login`. JWT tokens are signed with `SECRET_KEY` (auto-generated if unset, so set it for persistent sessions). File/thumbnail endpoints also accept `?token=` as a query parameter since `<img>`/`<video>` tags can't send headers.
|
||||
- Thumbnails are generated on first request and cached to disk (`THUMBNAIL_DIR`)
|
||||
- The scanner computes SHA-256 hashes to detect moved/renamed files and avoid re-processing
|
||||
- File watcher uses watchdog with per-library `PollingObserver` (necessary for Docker volumes)
|
||||
- `media_items.missing` flag is set when a scanned file no longer exists on disk
|
||||
- The frontend `build` command runs `tsc -b` first, which checks types across project references — type errors will block the build
|
||||
- Admin user is created automatically on first startup from `ADMIN_USERNAME`/`ADMIN_PASSWORD` env vars; additional users can be created via the Settings page by an admin
|
||||
|
||||
Reference in New Issue
Block a user