From 9144411e0fbd3f9db86b61c6473eca4baf29c8a3 Mon Sep 17 00:00:00 2001 From: Daniel Samson Date: Fri, 30 Oct 2026 15:34:50 +0000 Subject: [PATCH 1/5] fix: track frontend sample data hidden by overly broad data/ ignore rule frontend/src/data/sample.ts (imported by Home/CategoriesPage) was never committed because the root .gitignore ignored every path named data/. A fresh clone would have failed the frontend build. --- frontend/src/data/sample.ts | 113 ++++++++++++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 frontend/src/data/sample.ts diff --git a/frontend/src/data/sample.ts b/frontend/src/data/sample.ts new file mode 100644 index 0000000..7581478 --- /dev/null +++ b/frontend/src/data/sample.ts @@ -0,0 +1,113 @@ +/** + * Sample data used until the backend article endpoints are available + * (planned for a later milestone). The home page falls back to this + * dataset whenever `GET /api/v1/articles` is unavailable. + */ +import type { Article, Author, Category } from '../types'; + +export const sampleAuthors: Author[] = [ + { + id: 1, + name: 'Ada Lovelace', + email: 'ada@example.com', + bio: 'Writes about technology and computation.', + }, + { + id: 2, + name: 'Grace Hopper', + email: 'grace@example.com', + bio: 'Covers science and engineering.', + }, + { + id: 3, + name: 'Alan Turing', + email: 'alan@example.com', + bio: 'Follows sports and culture.', + }, +]; + +export const sampleCategories: Category[] = [ + { id: 1, name: 'Technology', slug: 'technology' }, + { id: 2, name: 'Science', slug: 'science' }, + { id: 3, name: 'Sports', slug: 'sports' }, + { id: 4, name: 'Culture', slug: 'culture' }, +]; + +const authorOf = (id: number): Author => sampleAuthors.find((a) => a.id === id) as Author; +const categoryOf = (id: number): Category => + sampleCategories.find((c) => c.id === id) as Category; + +export const sampleArticles: Article[] = [ + { + id: 1, + title: 'Inside the new wave of open-source language models', + content: + 'Open-source language models are closing the gap with proprietary systems, and the ecosystem around them is growing fast. Researchers now release pretrained weights alongside detailed training recipes, letting smaller teams fine-tune models for narrow tasks that once required large budgets. The result is a new layer of the AI stack: community-maintained tooling for evaluation, deployment, and safety testing that moves at a pace big vendors struggle to match. As hardware costs keep falling, expect the line between "research model" and "production model" to blur further this year.', + authorId: 1, + author: authorOf(1), + categoryId: 1, + category: categoryOf(1), + createdAt: '2025-06-02T09:30:00Z', + published: true, + }, + { + id: 2, + title: 'Fusion milestone: net energy gain repeated for the third time', + content: + 'Scientists have repeated a net-energy-gain fusion reaction for the third consecutive time, confirming that last months breakthrough was not a fluke. The latest run sustained the plasma for a record duration and produced energy output within a few percent of the original measurement. Engineers now say the remaining challenges are engineering, not physics: materials that survive repeated shots and power systems that deliver pulses on demand. A commercial demonstration plant could enter the design phase as early as next decade.', + authorId: 2, + author: authorOf(2), + categoryId: 2, + category: categoryOf(2), + createdAt: '2025-05-28T14:10:00Z', + published: true, + }, + { + id: 3, + title: 'City marathon sets record turnout as first-timers flood the course', + content: + 'More than 40,000 runners started this weekend city marathon, a record that organizers attributed to a wave of first-time participants. The 21-kilometer fun run sold out in under an hour, and volunteers reported the most positive start-line atmosphere in the events history. Pacing groups, music zones, and a free post-race breakfast kept the mood festive even in the rain. Officials are already planning capacity expansions for next year, with an eye on adding a night race.', + authorId: 3, + author: authorOf(3), + categoryId: 3, + category: categoryOf(3), + createdAt: '2025-05-25T08:00:00Z', + published: true, + }, + { + id: 4, + title: 'The quiet return of the neighborhood library', + content: + 'After years of budget cuts, the neighborhood library is staging an unlikely comeback. Community volunteers now staff the Saturday makerspace, where 3D printing, sewing machines, and a small recording studio are booked weeks in advance. Librarians report that circulation is up, but the real story is programming: repair cafés, language tables, and civic workshops that have made the building a second living room for the district. City planners are taking note, and two more branches are slated for renovation this fall.', + authorId: 1, + author: authorOf(1), + categoryId: 4, + category: categoryOf(4), + createdAt: '2025-05-20T17:45:00Z', + published: true, + }, + { + id: 5, + title: 'Rust keeps climbing the systems programming charts', + content: + 'Rust has moved up again in the annual systems programming survey, now the most-wanted language for kernel and infrastructure work among respondents. Adoption is no longer limited to startups: several large platforms report that new storage and networking services are written in Rust by default. The ecosystems memory-safety guarantees, combined with a mature async story, continue to draw engineers from C and C++. Tooling improvements in debugging and profiling have been the most cited reasons for teams crossing over this year.', + authorId: 2, + author: authorOf(2), + categoryId: 1, + category: categoryOf(1), + createdAt: '2025-05-15T11:20:00Z', + published: true, + }, + { + id: 6, + title: 'Ocean robots map the deepest trenches in record time', + content: + 'A fleet of autonomous underwater vehicles has completed the most detailed survey of the ocean trench yet, mapping 80 percent of the basin floor in six weeks. The robots, equipped with multibeam sonar and high-resolution cameras, collected terabytes of data that reveal previously unknown seamounts and hydrothermal vent fields. Biologists have already flagged three candidate species from the first batch of imagery. The team plans to return next winter with sampling landers to study the vent communities up close.', + authorId: 3, + author: authorOf(3), + categoryId: 2, + category: categoryOf(2), + createdAt: '2025-05-10T19:05:00Z', + published: true, + }, +]; -- 2.54.0 From ed7b30438e60ec23e7497b3b350a95ca44aa3cb4 Mon Sep 17 00:00:00 2001 From: Daniel Samson Date: Fri, 30 Oct 2026 15:35:08 +0000 Subject: [PATCH 2/5] feat: add Docker Compose developer environment with Makefile shortcuts (M4) - Root docker-compose.yml: backend (python:3.11-slim) + frontend (multi-stage node build -> nginx:alpine) on the newzy-network bridge network, frontend waits for the backend health check - Persistent SQLite via bind mount ./data/db -> /app/data/db - .env / .env.example documenting DATABASE_URL, DEBUG, BACKEND_CORS_ORIGINS and FRONTEND_API_URL - Makefile: dev, stop, restart, build, logs, status, backend-start, frontend-start, test, e2e, shell-backend, shell-frontend, clean - data/.gitignore keeps the data/ structure in git while excluding the database; root .gitignore drops the overly broad data/ rule and adds docker-compose.override.yml - backend: .gitignore covers .env.*, Dockerfile sets unbuffered python and pre-creates the db volume dir; frontend: new .dockerignore - README: full Docker setup docs (prerequisites, quick start, services, ports, network/storage, env vars, Makefile reference, troubleshooting) --- .env.example | 31 ++ .gitignore | 6 +- Makefile | 60 +++ README.md | 110 +++++- backend/.gitignore | 4 +- backend/Dockerfile | 16 +- data/.gitignore | 6 + data/keep_files.txt | 4 + docker-compose.yml | 41 +- frontend/.dockerignore | 18 + .../m4-setup-developer-environment-prompt.md | 372 ++++++++++++++++++ 11 files changed, 653 insertions(+), 15 deletions(-) create mode 100644 .env.example create mode 100644 Makefile create mode 100644 data/.gitignore create mode 100644 data/keep_files.txt create mode 100644 frontend/.dockerignore create mode 100644 milestones/m4-setup-developer-environment-prompt.md diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..49836bf --- /dev/null +++ b/.env.example @@ -0,0 +1,31 @@ +# newzy — environment variable template. +# +# Copy to `.env` and adjust as needed: +# +# cp .env.example .env +# +# `docker compose` in this directory reads `.env` automatically. `.env` is +# excluded from version control (see .gitignore) — never commit secrets. +# The backend's own defaults are documented in `backend/.env.example`. + +# --- Database ------------------------------------------------------------- +# SQLite database location (SQLAlchemy URL, relative to the backend's +# working directory). Inside the Docker image this resolves to +# /app/data/db/newzy.db, which is bind-mounted to ./data/db on the host. +DATABASE_URL=sqlite:///./data/db/newzy.db + +# --- Backend ---------------------------------------------------------------- +# Enable debug mode (verbose logs; keep off in production). +DEBUG=false +# Comma-separated list of origins the backend allows for CORS. The Docker +# frontend proxies /api (same-origin, no CORS needed); this mainly matters +# when developing the frontend directly on http://localhost:5173. +BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:5173 + +# --- Frontend ---------------------------------------------------------------- +# Base URL the frontend uses to reach the backend API. +# /api -> relative (recommended: the Vite dev server and the +# Docker Nginx config both proxy /api to the backend) +# http://host:port -> absolute (cross-origin; the origin must be listed in +# BACKEND_CORS_ORIGINS) +FRONTEND_API_URL=/api diff --git a/.gitignore b/.gitignore index dbb5ffa..71aa9f2 100644 --- a/.gitignore +++ b/.gitignore @@ -43,8 +43,10 @@ coverage/ .DS_Store Thumbs.db -# Local data / uploads -data/ +# Docker (local per-developer overrides; .dockerignore files are committed) +docker-compose.override.yml + +# Local data / uploads (data/ is managed by data/.gitignore) uploads/ *.sqlite *.db diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..fef6f03 --- /dev/null +++ b/Makefile @@ -0,0 +1,60 @@ +# newzy — development shortcuts (docker compose under the hood). +# Run `make help` (or just `make`) for the list of targets. + +COMPOSE ?= docker compose + +.DEFAULT_GOAL := help + +.PHONY: help dev stop restart build logs status backend-start frontend-start \ + test test-frontend test-backend e2e shell-backend shell-frontend clean + +help: ## Show this help + @grep -E '^[a-zA-Z_-]+:.*?## ' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-15s\033[0m %s\n", $$1, $$2}' + +dev: ## Build (if needed) and start both services in the background + $(COMPOSE) up -d --build + +stop: ## Stop and remove containers (local data in ./data is kept) + $(COMPOSE) down + +restart: ## Recreate and start both services + $(COMPOSE) down + $(COMPOSE) up -d --build + +build: ## Rebuild all images from scratch (no cache) + $(COMPOSE) build --no-cache + +logs: ## Follow the logs of both services + $(COMPOSE) logs -f backend frontend + +status: ## Show the status of both services + $(COMPOSE) ps + +backend-start: ## Build (if needed) and start the backend only + $(COMPOSE) up -d backend + +frontend-start: ## Build (if needed) and start the frontend only + $(COMPOSE) up -d frontend + +test: test-frontend test-backend ## Run all unit tests (frontend + backend) + +test-frontend: ## Run frontend unit tests (requires Node.js 18+) + cd frontend && npm run test + +test-backend: ## Run backend tests (uses backend/.venv if present, else system pytest) + cd backend && if [ -x .venv/bin/pytest ]; then .venv/bin/pytest; else pytest; fi + +e2e: ## Run Playwright E2E tests (frontend/playwright; API calls are mocked) + cd frontend && npm run e2e + +shell-backend: ## Open a shell inside the running backend container + $(COMPOSE) exec backend bash + +shell-frontend: ## Open a shell inside the running frontend container + $(COMPOSE) exec frontend sh + +clean: ## Stop everything; remove containers, volumes and local data + $(COMPOSE) down -v --remove-orphans + rm -rf data/ + git checkout -- data/ 2>/dev/null || true + docker image prune -f diff --git a/README.md b/README.md index 66267ca..786b8ce 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,8 @@ | M1 | Git project setup | Done | | M2 | Backend setup (FastAPI) | Done | | M3 | Frontend setup (React + Vite) | Done | -| M4+ | News application features | Planned | +| M4 | Developer environment (Docker) | Done | +| M5+ | News application features | Planned | See [milestones/](milestones/) for milestone prompts and progress tracking. @@ -44,17 +45,112 @@ git push -u origin feature/ Full contribution guidelines, including branching, merging, and rebase workflows, are in [CONTRIBUTING.md](CONTRIBUTING.md). -## Running the application +## Developer environment (Docker Compose) + +The repository root ships a complete Docker Compose setup: one command starts +the FastAPI backend and the Nginx-served production frontend, with a +persistent SQLite database on the host. + +### Prerequisites + +- **Docker** (Docker Desktop or the docker engine + compose plugin v2), with the daemon running +- Optional (only for `make test` outside Docker): **Node.js 18+** and **Python 3.11+** + +### Quick start ```bash -# Full stack (backend :8000 + frontend :3000) -docker compose up --build +# 1. Configure the environment (defaults are fine for local development) +cp .env.example .env + +# 2. Build (if needed) and start both services in the background +make dev + +# 3. Open the application +# Frontend: http://localhost:3000 +# Backend: http://localhost:8000 (Swagger docs: http://localhost:8000/api/v1/docs) + +# 4. Stop everything (the database in ./data is kept) +make stop ``` -Or run each half locally — see the component READMEs for details: +### Services -- [frontend/README.md](frontend/README.md) — `npm run dev` (port 5173) -- [backend/README.md](backend/README.md) — `uvicorn main:app --reload` (port 8000) +| Service | Build context | Image base | What it does | +| ---------- | ------------- | ----------------- | -------------------------------------------------------- | +| `backend` | `./backend` | `python:3.11-slim`| FastAPI app (uvicorn), creates the SQLite schema on startup | +| `frontend` | `./frontend` | `node:20-alpine` → `nginx:1.27-alpine` (multi-stage) | Builds the Vite bundle, serves it via Nginx with SPA routing and an `/api` proxy to the backend | + +### Port mappings + +| Host port | Container | Service | +| --------- | --------- | -------- | +| `3000` | `80` | frontend (Nginx) | +| `8000` | `8000` | backend (uvicorn) | + +### Networking and storage + +- Both services share the bridge network `newzy-network` (subnet `172.28.0.0/16`), + so the frontend reaches the backend by service name (`http://backend:8000`). +- The SQLite database is stored on the host at [`data/db/newzy.db`](data/) via a + bind mount (`./data/db` → `/app/data/db`). It is excluded from version control + (see `data/.gitignore`) and survives `make stop`/`make restart`. +- `frontend` only starts once `backend` reports healthy (`/health`), so + `docker compose up` never serves a frontend with a dead API. + +### Environment variables + +`docker compose` reads [`.env`](.env) from the project root (template: +[`.env.example`](.env.example)). Never commit `.env` or real secrets. + +| Variable | Description | Default | Required | +| --------------------- | ---------------------------------------- | --------------------------------------------------- | -------- | +| `DATABASE_URL` | SQLite database path (SQLAlchemy URL) | `sqlite:///./data/db/newzy.db` | Yes | +| `DEBUG` | Debug mode flag | `false` | No | +| `BACKEND_CORS_ORIGINS`| Comma-separated allowed CORS origins | `http://localhost:3000,http://localhost:5173` | No | +| `FRONTEND_API_URL` | Backend API base URL (relative or absolute) | `/api` | No | + +### Makefile shortcuts + +| Command | What it does | +| ---------------------- | ------------------------------------------------------- | +| `make dev` | Build (if needed) and start both services in the background | +| `make stop` | Stop and remove containers (data kept) | +| `make restart` | Recreate and start both services | +| `make build` | Rebuild all images from scratch | +| `make logs` | Follow logs of both services | +| `make status` | Show service status | +| `make backend-start` | Start the backend only | +| `make frontend-start` | Start the frontend only | +| `make test` | Run all unit tests (frontend vitest + backend pytest) | +| `make e2e` | Run Playwright E2E tests (API calls mocked) | +| `make shell-backend` | Open a shell in the backend container | +| `make shell-frontend` | Open a shell in the frontend container | +| `make clean` | Stop everything, remove containers, volumes and `data/` | + +### Troubleshooting + +- **Port already in use** (`bind: address already in use`): stop the other + process (`lsof -i :3000` / `lsof -i :8000`) or change the host port in + `docker-compose.yml` (e.g. `"3001:80"`). +- **Frontend starts but shows errors / 502 on API calls**: the backend is not + healthy yet — check `make logs backend`. The frontend waits for the backend + health check on startup; after a slow start, reload the page. +- **`docker compose` not found**: install the Compose v2 plugin + (`docker compose version` must print a version). +- **Database reset**: `make clean` removes `data/` (including the SQLite file); + tables are recreated on the next backend start. +- **Slow builds on first run**: the first `make dev` pulls the base images and + installs dependencies (~5 minutes). Subsequent builds use the Docker layer + cache and finish in seconds. +- **Ownership issues in `data/`** (e.g. after running Docker as root): restore + with `sudo chown -R $(id -un):$(id -gn) data/`. +- **Windows**: use WSL2 for best performance; **macOS**: allow Docker Desktop + sufficient disk space (50 GB+ recommended). + +### Running without Docker + +- Frontend: [`frontend/README.md`](frontend/README.md) — `npm run dev` (port 5173, proxies `/api` to :8000) +- Backend: [`backend/README.md`](backend/README.md) — `uvicorn main:app --reload` (port 8000) ## Documentation diff --git a/backend/.gitignore b/backend/.gitignore index cc5aa29..8a7a0f4 100644 --- a/backend/.gitignore +++ b/backend/.gitignore @@ -3,8 +3,10 @@ __pycache__/ *.py[cod] *.egg-info/ -# Environment files +# Environment files (keep the committed template) .env +.env.* +!.env.example .venv/ venv/ diff --git a/backend/Dockerfile b/backend/Dockerfile index 238f2d9..37d023e 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -1,15 +1,25 @@ +# newzy backend — FastAPI + SQLite. +# Orchestration lives in the repository root: docker-compose.yml. + FROM python:3.11-slim +# Unbuffered logs, no .pyc files in the image, no pip cache. +ENV PYTHONUNBUFFERED=1 \ + PYTHONDONTWRITEBYTECODE=1 \ + PIP_NO_CACHE_DIR=1 + WORKDIR /app -# Install dependencies first to leverage Docker layer caching +# Install dependencies first to leverage Docker layer caching. COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt -# Copy application code +# Copy application code (dev-only files excluded by .dockerignore). COPY . . -# SQLite database lives on a mounted volume (see docker-compose.yml) +# The SQLite database lives on a bind-mounted volume (see docker-compose.yml); +# ensure the directory exists even before the volume is attached. +RUN mkdir -p /app/data/db VOLUME /app/data/db # Expose port diff --git a/data/.gitignore b/data/.gitignore new file mode 100644 index 0000000..dcb4d7a --- /dev/null +++ b/data/.gitignore @@ -0,0 +1,6 @@ +# Exclude everything under data/ from version control (SQLite database, +# uploads, ...) except the keep file below, so the directory structure +# (data/db/) survives a fresh clone. +* +!.gitignore +!keep_files.txt diff --git a/data/keep_files.txt b/data/keep_files.txt new file mode 100644 index 0000000..4f72d13 --- /dev/null +++ b/data/keep_files.txt @@ -0,0 +1,4 @@ +# This file is tracked by git so the data/ directory structure (data/db/) +# is preserved in fresh clones. Everything else under data/ — the SQLite +# database (data/db/newzy.db), uploads, and other local state — is ignored +# by data/.gitignore and recreated at runtime. diff --git a/docker-compose.yml b/docker-compose.yml index 3586ad2..070df26 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,23 +1,60 @@ +# newzy — full application stack (FastAPI backend + Nginx frontend). +# +# make dev # build (if needed) and start both services in the background +# make stop # stop and remove the containers (local data is kept) +# make clean # stop everything and remove containers, volumes and data/ +# +# Environment variables are read from `.env` in this directory (template: +# `.env.example`). See README.md for the complete developer documentation. +# +# The `version` key is intentionally omitted: it is obsolete in Compose v2 +# and only produces a deprecation warning. + services: backend: - build: ./backend + build: + context: ./backend + dockerfile: Dockerfile ports: - "8000:8000" volumes: + # Persistent SQLite database: ./data/db on the host -> /app/data/db + # inside the container (excluded from git, see data/.gitignore). - ./data/db:/app/data/db environment: - DATABASE_URL=sqlite:///./data/db/newzy.db + - DEBUG=false + - BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:5173 healthcheck: test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] interval: 30s timeout: 5s retries: 3 + start_period: 10s + networks: + - newzy-network restart: unless-stopped + frontend: - build: ./frontend + build: + context: ./frontend + dockerfile: Dockerfile ports: - "3000:80" depends_on: backend: condition: service_healthy + networks: + - newzy-network restart: unless-stopped + +networks: + newzy-network: + driver: bridge + ipam: + config: + - subnet: 172.28.0.0/16 + +volumes: + db-data: + name: newzy-db-data diff --git a/frontend/.dockerignore b/frontend/.dockerignore new file mode 100644 index 0000000..d32fbb2 --- /dev/null +++ b/frontend/.dockerignore @@ -0,0 +1,18 @@ +# Keep the image small: exclude dev-only files from the build context. +node_modules/ +dist/ +coverage/ +test-results/ +playwright-report/ +playwright/.cache/ +.env +.env.* +!.env.example +.git/ +.gitignore +Dockerfile +.dockerignore +docker-compose.yml +README.md +*.log +.DS_Store diff --git a/milestones/m4-setup-developer-environment-prompt.md b/milestones/m4-setup-developer-environment-prompt.md new file mode 100644 index 0000000..6858de1 --- /dev/null +++ b/milestones/m4-setup-developer-environment-prompt.md @@ -0,0 +1,372 @@ +# M4: Setup Developer Environment + +## Prompt + +Set up a complete developer environment for **newzy** news web application with Docker Compose orchestration. Follow these steps: + +1. Create `docker-compose.yml` at project root (`newzy/docker-compose.yml`) with all services: + ```yaml + version: '3.8' + + services: + backend: + build: ./backend + ports: + - "8000:8000" + volumes: + - ./data/db:/app/data/db + environment: + - DATABASE_URL=sqlite:///./data/db/newzy.db + - DEBUG=false + + frontend: + build: ./frontend + ports: + - "3000:80" + depends_on: + - backend + + networks: + newzy-network: + driver: bridge + + volumes: + db-data: + ``` + +2. Create `.env.example` file documenting all required environment variables: + - DATABASE_URL (SQLite path) + - DEBUG (boolean, optional) + - BACKEND_CORS_ORIGINS (comma-separated, default: http://localhost:3000) + - FRONTEND_API_URL (relative /api or absolute) + +3. Create `.env` file with default development values: + ```bash + DATABASE_URL=sqlite:///./data/db/newzy.db + DEBUG=false + BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:5173 + FRONTEND_API_URL=/api + ``` + +4. Update `backend/.gitignore` to exclude `.env` and production data: + ```python + .env + .env.* + data/ + ``` + +5. Create development scripts in project root using Makefile or shell script: + - `dev` - Start both services in background + - `stop` - Stop all services + - `restart` - Restart all services + - `backend-start` - Start backend only + - `frontend-start` - Start frontend only + - `test` - Run all tests (unit + E2E) + - `clean` - Remove containers and volumes + +6. Add `Makefile` for command shortcuts: + ```makefile + .PHONY: dev stop restart backend-start frontend-start test clean + + dev: + docker compose up -d --build + + stop: + docker compose down + + restart: + docker compose down + docker compose up -d --build + + backend-start: + docker compose up -d backend + + frontend-start: + docker compose up -d frontend + + test: + npm run test # frontend + cd backend && pytest # backend + + clean: + docker compose down -v + rm -rf data/ + docker image prune -f + ``` + +7. Create `backend/Dockerfile` with development optimizations: + - Copy only required files + - Install dependencies efficiently + - Use slim Python base image + - Expose port 8000 + +8. Update `frontend/Dockerfile` to use production Nginx: + - Multi-stage build (build stage + nginx serve stage) + - Nginx configuration for SPA routing + - Production-optimized static file serving + +9. Create `.gitignore` at project root excluding: + ``` + # Dependencies + node_modules/ + *.egg-info/ + + # Environment files + .env + .env.local + .env.*.local + + # IDE settings + .idea/ + .vscode/ + *.swp + *.swo + + # Docker artifacts (optional) + .dockerignore + docker-compose.override.yml + ``` + +10. Create `data/.gitignore` to exclude SQLite database from version control: + ``` + * + !keep_files.txt + ``` + +11. Document setup process in `README.md`: + - Prerequisites (Docker, Node.js 18+) + - Quick start commands + - Service descriptions + - Port mappings + - Network configuration + - Troubleshooting guide + +12. Create `.dockerignore` files for both backend and frontend to exclude unnecessary files during builds: + ``` + .git/ + .env + __pycache__/ + *.pyc + node_modules/ + dist/ + .pytest_cache/ + ``` + +Remember: Focus ONLY on developer environment setup. No application code changes required. + +## Description + +This milestone sets up a complete Docker Compose development environment for the newzy news web application. The scope includes orchestrating both backend and frontend services, environment variable management, and streamlined development commands—no application logic changes or business feature implementation. + +**Purpose**: Provide developers with a consistent, reproducible local development environment using Docker that matches the production setup as closely as possible. + +**Target Audience**: Developers joining the project who need quick access to running services without manual installation of Python, Node.js, databases, or Nginx. + +**Expected Outcomes**: A working docker-compose.yml at project root that can start all services with a single command, proper environment configuration, and development workflow automation via Makefile. + +## Acceptance Criteria + +- [ ] `docker-compose.yml` at project root configures both backend and frontend services +- [ ] Backend service builds from `./backend` directory +- [ ] Frontend service builds from `./frontend` directory +- [ ] Port mappings configured: 3000 for frontend, 8000 for backend +- [ ] Docker network defined for inter-service communication +- [ ] Volume mounted for persistent SQLite database at `/data/db` +- [ ] `.env.example` file documents all environment variables +- [ ] `.env` file provides default development configuration +- [ ] `backend/Dockerfile` optimized for production use +- [ ] `frontend/Dockerfile` uses multi-stage build with Nginx +- [ ] Makefile or shell scripts provide dev, stop, restart commands +- [ ] `data/.gitignore` excludes database from version control +- [ ] `.dockerignore` files exist for both frontend and backend +- [ ] Project root `.gitignore` excludes env files and build artifacts +- [ ] README.md documents docker setup with quick start guide + +## Technical Details + +### docker-compose.yml (Project Root) + +```yaml +version: '3.8' + +services: + backend: + build: + context: ./backend + dockerfile: Dockerfile + ports: + - "8000:8000" + volumes: + - ./data/db:/app/data/db + environment: + - DATABASE_URL=sqlite:///./data/db/newzy.db + - DEBUG=false + - BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:5173 + depends_on: + backend-db: + condition: service_healthy + networks: + - newzy-network + restart: unless-stopped + + frontend: + build: + context: ./frontend + dockerfile: Dockerfile + ports: + - "3000:80" + depends_on: + - backend + networks: + - newzy-network + restart: unless-stopped + +networks: + newzy-network: + driver: bridge + ipam: + config: + - subnet: 172.28.0.0/16 + +volumes: + db-data: + name: newzy-db-data +``` + +### Environment Variables (.env.example) + +| Variable | Description | Default | Required | +|----------|-------------|---------|----------| +| DATABASE_URL | SQLite database path | sqlite:///./data/db/newzy.db | Yes | +| DEBUG | Debug mode flag | false | No | +| BACKEND_CORS_ORIGINS | Allowed frontend origins | http://localhost:3000 | No | +| FRONTEND_API_URL | Backend API base URL | /api | No | + +### Development Commands (Makefile) + +```makefile +.PHONY: dev stop restart test clean build + +dev: + docker compose up -d --build backend frontend + +stop: + docker compose down + +restart: + docker compose down + docker compose up -d --build backend frontend + +test: + @echo "Running frontend tests..." + npm run test + @echo "Running backend tests..." + docker exec frontend npm run test || \ + docker exec backend pytest + +clean: + docker compose down -v + rm -rf data/ + docker images | grep -E "(newzy|python|node)" | awk '{print $$3}' | xargs docker rmi + +build: + docker compose build --no-cache + +logs: + docker compose logs -f backend frontend + +shell-backend: + docker exec -it backend bash + +shell-frontend: + docker exec -it frontend sh +``` + +### Directory Structure with Docker Setup + +``` +newzy/ +├── data/ # Local SQLite data directory +│ └── db/ +│ └── newzy.db # Persisted database (excluded from git) +├── backend/ +│ ├── Dockerfile +│ ├── requirements.txt +│ ├── .gitignore +│ └── pytest.ini +├── frontend/ +│ ├── Dockerfile +│ ├── docker-compose.yml # Frontend-specific override (optional) +│ └── package.json +├── docker-compose.yml # Main orchestration file +├── .env # Development environment variables +├── .env.example # Template for .env +├── Makefile # Development shortcuts +├── .dockerignore # Exclude files from build context +└── data/.gitignore # Exclude database from git +``` + +### Multi-stage Build Strategy + +**Backend Dockerfile:** +- Base: `python:3.11-slim` +- Install dependencies with `pip install --no-cache-dir` +- Copy only production code and requirements +- Expose port 8000 + +**Frontend Dockerfile:** +- Stage 1: `node:20-alpine` → Build frontend with Vite +- Stage 2: `nginx:alpine` → Serve built static files +- Nginx config routes all requests to index.html for SPA + +### Service Communication Flow + +``` +Browser (localhost:3000) + ↓ HTTP Request +Frontend Container (newzy-network:80) + ↓ Forwarded to /api +Backend Container (newzy-network:8000) + ↓ Connects to SQLite +Volume: data/db/newzy.db +``` + +## QA Notes + +### Testing Checklist +- [ ] `docker compose up` starts both services without errors +- [ ] Frontend accessible at http://localhost:3000 +- [ ] Backend accessible at http://localhost:8000 +- [ ] Health endpoints respond correctly +- [ ] Database persists across service restarts +- [ ] `.env.example` contains all documented variables +- [ ] Makefile commands work (dev, stop, restart, clean) +- [ ] `data/` directory excluded from git commits +- [ ] `.gitignore` excludes environment files + +### Security Considerations +- Never commit `.env` file to version control +- Use `.env.example` as template for new developers +- SQLite database stored locally, not in container (volume mounted) +- CORS configured with specific origins +- No production secrets exposed by default + +### Performance Notes +- `--build` flag only when needed (avoid rebuilds on dev) +- Docker cache leveraged for incremental builds +- SQLite file storage faster than network databases for development +- Nginx serves static files efficiently in production + +### Known Limitations +- Requires Docker Desktop or equivalent installed locally +- Mac users need sufficient disk space (~50GB recommended) +- Windows WSL2 required for best performance +- No GPU acceleration (CPU-based only) +- Production databases should use PostgreSQL, not SQLite + +### Success Metrics +- `docker compose up` completes in under 5 minutes on first run +- Services restart within 10 seconds subsequent runs +- Development environment identical to staging/production setup +- Zero manual configuration required for new developers +- Makefile shortcuts reduce repetitive Docker commands -- 2.54.0 From b186d0f79780489dd1bfb57bbe81860452bd8573 Mon Sep 17 00:00:00 2001 From: Daniel Samson Date: Fri, 30 Oct 2026 17:03:00 +0000 Subject: [PATCH 3/5] feat: add JWT authentication with auth pages and tests (M5) Backend (FastAPI): - core/auth.py: PBKDF2-HMAC-SHA256 password hashing (120k iterations, random salt), HS256 JWT creation/verification (7-day expiry, HN_SECRET_KEY via config) and get_current_user Bearer dependency - models/user.py: User model (username unique/indexed, password_hash, created_at); schemas/auth.py: register/login/token/user schemas - api/v1/auth.py: POST /api/v1/auth/register (201), /login, /logout (204), GET /me; 400 on duplicate username, 401 on bad credentials, invalid/expired/unknown tokens - requirements: PyJWT; env templates + docker-compose expose HN_SECRET_KEY (dev default, override in production) - tests: 24 new backend tests (hashing, tokens, all endpoints) Frontend (React + TypeScript): - api/client.ts: AUTH_TOKEN localStorage persistence, automatic Bearer token attachment, 401 clears the stored token, typed login/register/logout/me helpers - auth.tsx: AuthProvider (session restore + login/register/logout) and RequireAuth route guard - pages: Login, Register, SignOut and a protected /account placeholder; header shows sign-in/register or user/sign-out - styles: auth component classes in globals.css - tests: unit tests for the client, provider and pages; Playwright E2E spec covering register/login/logout, session restore, invalid token cleanup and protected-route redirects (API mocked) Note: the milestone's /api/auth/* paths map to the project's established /api/v1/* prefix (see M2); the HN_SECRET_KEY default is newzy-dev-secret-change-me. --- .env.example | 3 + backend/.env.example | 4 + backend/api/v1/__init__.py | 4 + backend/api/v1/auth.py | 70 +++ backend/config.py | 6 + backend/core/auth.py | 97 ++++ backend/models/__init__.py | 3 +- backend/models/user.py | 34 ++ backend/requirements.txt | 3 + backend/schemas/__init__.py | 5 + backend/schemas/auth.py | 39 ++ backend/tests/test_auth.py | 198 ++++++++ backend/tests/test_models.py | 21 +- data/.gitignore | 3 + docker-compose.yml | 3 + frontend/playwright/e2e/auth.spec.ts | 198 ++++++++ frontend/src/App.tsx | 46 +- frontend/src/api/client.ts | 37 +- frontend/src/assets/styles/globals.css | 45 ++ frontend/src/auth.tsx | 116 +++++ frontend/src/components/ui/Header.tsx | 49 +- frontend/src/pages/Account.tsx | 21 + frontend/src/pages/Login.tsx | 114 +++++ frontend/src/pages/Register.tsx | 128 +++++ frontend/src/pages/SignOut.tsx | 28 ++ frontend/src/tests/Header.test.tsx | 56 ++- frontend/src/tests/Layout.test.tsx | 13 +- frontend/src/tests/auth.test.tsx | 189 +++++++ frontend/src/tests/client.auth.test.ts | 122 +++++ frontend/src/tests/pages/Login.test.tsx | 104 ++++ frontend/src/tests/pages/Register.test.tsx | 116 +++++ frontend/src/tests/setup.ts | 46 +- frontend/src/tests/utils.tsx | 33 +- frontend/src/types/auth.ts | 15 + milestones/m5-setup-authentication-prompt.md | 489 +++++++++++++++++++ 35 files changed, 2422 insertions(+), 36 deletions(-) create mode 100644 backend/api/v1/auth.py create mode 100644 backend/core/auth.py create mode 100644 backend/models/user.py create mode 100644 backend/schemas/auth.py create mode 100644 backend/tests/test_auth.py create mode 100644 frontend/playwright/e2e/auth.spec.ts create mode 100644 frontend/src/auth.tsx create mode 100644 frontend/src/pages/Account.tsx create mode 100644 frontend/src/pages/Login.tsx create mode 100644 frontend/src/pages/Register.tsx create mode 100644 frontend/src/pages/SignOut.tsx create mode 100644 frontend/src/tests/auth.test.tsx create mode 100644 frontend/src/tests/client.auth.test.ts create mode 100644 frontend/src/tests/pages/Login.test.tsx create mode 100644 frontend/src/tests/pages/Register.test.tsx create mode 100644 frontend/src/types/auth.ts create mode 100644 milestones/m5-setup-authentication-prompt.md diff --git a/.env.example b/.env.example index 49836bf..45a16a3 100644 --- a/.env.example +++ b/.env.example @@ -17,6 +17,9 @@ DATABASE_URL=sqlite:///./data/db/newzy.db # --- Backend ---------------------------------------------------------------- # Enable debug mode (verbose logs; keep off in production). DEBUG=false +# JWT signing key (HS256) used by the backend auth endpoints. Change this +# before deploying publicly — the dev default is not secret. +HN_SECRET_KEY=newzy-dev-secret-change-me # Comma-separated list of origins the backend allows for CORS. The Docker # frontend proxies /api (same-origin, no CORS needed); this mainly matters # when developing the frontend directly on http://localhost:5173. diff --git a/backend/.env.example b/backend/.env.example index 3ed2c43..109ff63 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -5,3 +5,7 @@ DATABASE_URL=sqlite:///./data/db/newzy.db # Comma-separated list of origins allowed by CORS (frontend dev server etc.) CORS_ORIGINS=http://localhost:3000,http://127.0.0.1:3000 + +# JWT signing key (HS256). Change this in production — tokens signed with +# the dev default must be considered insecure. +HN_SECRET_KEY=newzy-dev-secret-change-me diff --git a/backend/api/v1/__init__.py b/backend/api/v1/__init__.py index 4e70e50..49dfc53 100644 --- a/backend/api/v1/__init__.py +++ b/backend/api/v1/__init__.py @@ -5,11 +5,15 @@ Mounted under ``/api/v1`` (see ``core.app.create_app``). from fastapi import APIRouter +from api.v1 import auth as auth_routes from config import APP_NAME, APP_VERSION from schemas import HealthResponse, VersionResponse router = APIRouter() +# Authentication (register / login / logout / me) under /api/v1/auth. +router.include_router(auth_routes.router) + @router.get("/health", response_model=HealthResponse, summary="Service health check") def get_health() -> HealthResponse: diff --git a/backend/api/v1/auth.py b/backend/api/v1/auth.py new file mode 100644 index 0000000..756f6ec --- /dev/null +++ b/backend/api/v1/auth.py @@ -0,0 +1,70 @@ +"""Authentication endpoints: register, login, logout, me. + +Passwords are stored only as PBKDF2-HMAC-SHA256 hashes (``core.auth``). +Sessions are stateless: the client keeps the JWT and sends it back as a +Bearer token, so ``logout`` is a server-side no-op (best-effort 204). +""" + +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.exc import IntegrityError +from sqlalchemy.orm import Session + +from core import auth +from db.session import get_db +from models import User +from schemas import LoginIn, RegisterIn, TokenOut, UserOut + +router = APIRouter(prefix="/auth", tags=["auth"]) + + +def _user_by_username(db: Session, username: str) -> User | None: + return db.query(User).filter(User.username == username).first() + + +@router.post( + "/register", + response_model=TokenOut, + status_code=status.HTTP_201_CREATED, + summary="Register a new account", +) +def register(payload: RegisterIn, db: Session = Depends(get_db)) -> TokenOut: + """Create a user (password hashed with PBKDF2) and issue a JWT.""" + if _user_by_username(db, payload.username) is not None: + raise HTTPException(status_code=400, detail="Username already exists") + user = User( + username=payload.username, + password_hash=auth.hash_password(payload.password), + ) + db.add(user) + try: + db.commit() + except IntegrityError: + # Lost the race against a concurrent registration. + db.rollback() + raise HTTPException(status_code=400, detail="Username already exists") from None + return TokenOut(token=auth.create_token(user.username), username=user.username) + + +@router.post("/login", response_model=TokenOut, summary="Log in with credentials") +def login(payload: LoginIn, db: Session = Depends(get_db)) -> TokenOut: + """Verify the credentials and issue a JWT.""" + user = _user_by_username(db, payload.username) + if user is None or not auth.verify_password(payload.password, user.password_hash): + raise HTTPException(status_code=401, detail="Invalid username or password") + return TokenOut(token=auth.create_token(user.username), username=user.username) + + +@router.post( + "/logout", + status_code=status.HTTP_204_NO_CONTENT, + summary="Log out (stateless)", +) +def logout(current_user: str = Depends(auth.get_current_user)) -> None: + """Best-effort logout: the client simply discards its token.""" + return None + + +@router.get("/me", response_model=UserOut, summary="Current authenticated user") +def me(current_user: str = Depends(auth.get_current_user)) -> UserOut: + """Return the user the Bearer token belongs to.""" + return UserOut(username=current_user) diff --git a/backend/config.py b/backend/config.py index 9f0edd3..adcf3d8 100644 --- a/backend/config.py +++ b/backend/config.py @@ -21,6 +21,10 @@ DEFAULT_DATABASE_URL = "sqlite:///./data/db/newzy.db" # Default origins allowed by CORS (frontend dev servers). DEFAULT_CORS_ORIGINS = "http://localhost:3000,http://127.0.0.1:3000" +# Default JWT signing key (override via HN_SECRET_KEY in production — +# never run a public deployment with the dev default). +DEFAULT_SECRET_KEY = "newzy-dev-secret-change-me" + class Settings: """Runtime settings loaded from the environment.""" @@ -32,6 +36,8 @@ class Settings: for origin in os.getenv("CORS_ORIGINS", DEFAULT_CORS_ORIGINS).split(",") if origin.strip() ] + # JWT signing key for auth tokens (see core.auth). + self.secret_key: str = os.getenv("HN_SECRET_KEY", DEFAULT_SECRET_KEY) @property def is_sqlite(self) -> bool: diff --git a/backend/core/auth.py b/backend/core/auth.py new file mode 100644 index 0000000..aa4c7ec --- /dev/null +++ b/backend/core/auth.py @@ -0,0 +1,97 @@ +"""Authentication primitives. + +- Passwords are stored only as PBKDF2-HMAC-SHA256 hashes with a random + per-password salt (never in plaintext). +- Sessions are stateless JWTs (HS256) signed with ``HN_SECRET_KEY`` + (see ``config.Settings``), valid for 7 days. +- ``get_current_user`` is the FastAPI dependency that validates the + ``Authorization: Bearer `` header and returns the username. +""" + +import hashlib +import secrets +import time + +import jwt +from fastapi import Depends, HTTPException +from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer +from sqlalchemy.orm import Session + +from config import get_settings +from db.session import get_db +from models import User + +# HS256 JWTs signed with the application secret. The dev default keeps +# tokens valid across container restarts; override via HN_SECRET_KEY. +SECRET_KEY = get_settings().secret_key +ALGORITHM = "HS256" +TOKEN_TTL_SECONDS = 7 * 24 * 60 * 60 # 7 days + +# PBKDF2-HMAC-SHA256 parameters (120,000 iterations per OWASP guidance). +PBKDF2_ITERATIONS = 120_000 + +# ``auto_error=False`` so missing headers produce our own 401 envelope +# instead of FastAPI's default 403. +_bearer = HTTPBearer(auto_error=False) + + +def hash_password(password: str) -> str: + """Hash ``password`` with a fresh random salt. + + Returns ``"$"`` where ``salt`` is 32 hex chars + (``secrets.token_hex(16)``) and ``digest`` is the PBKDF2 hex digest. + """ + salt = secrets.token_hex(16) + digest = hashlib.pbkdf2_hmac( + "sha256", password.encode(), bytes.fromhex(salt), PBKDF2_ITERATIONS + ).hex() + return f"{salt}${digest}" + + +def verify_password(password: str, stored: str) -> bool: + """Verify ``password`` against a stored ``"$"`` hash. + + The comparison is constant-time (``secrets.compare_digest``). + Malformed stored values simply verify as ``False``. + """ + try: + salt, digest = stored.split("$", 1) + salt_bytes = bytes.fromhex(salt) + except ValueError: + return False + candidate = hashlib.pbkdf2_hmac( + "sha256", password.encode(), salt_bytes, PBKDF2_ITERATIONS + ).hex() + return secrets.compare_digest(candidate, digest) + + +def create_token(username: str) -> str: + """Create a signed JWT for ``username`` (``sub``/``iat``/``exp``).""" + now = int(time.time()) + payload = { + "sub": username, + "iat": now, + "exp": now + TOKEN_TTL_SECONDS, + } + return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM) + + +def get_current_user( + credentials: HTTPAuthorizationCredentials | None = Depends(_bearer), + db: Session = Depends(get_db), +) -> str: + """Validate the Bearer token and return the username. + + Raises 401 when the header is missing, the token is invalid/expired + or was issued to a user that no longer exists. + """ + if credentials is None: + raise HTTPException(status_code=401, detail="Not authenticated") + try: + payload = jwt.decode(credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM]) + except jwt.PyJWTError as exc: + raise HTTPException(status_code=401, detail="Invalid or expired token") from exc + username = payload.get("sub") + if not username or db.query(User).filter(User.username == username).first() is None: + raise HTTPException(status_code=401, detail="Unknown user") + return username diff --git a/backend/models/__init__.py b/backend/models/__init__.py index 04accf2..db1aaae 100644 --- a/backend/models/__init__.py +++ b/backend/models/__init__.py @@ -4,5 +4,6 @@ from models.article import Article from models.author import Author from models.base import Base from models.category import Category, slugify +from models.user import User -__all__ = ["Article", "Author", "Base", "Category", "slugify"] +__all__ = ["Article", "Author", "Base", "Category", "User", "slugify"] diff --git a/backend/models/user.py b/backend/models/user.py new file mode 100644 index 0000000..f82bd30 --- /dev/null +++ b/backend/models/user.py @@ -0,0 +1,34 @@ +"""User account model (JWT-based authentication, see ``core.auth``).""" + +from __future__ import annotations + +from datetime import datetime, timezone + +from sqlalchemy import DateTime, String +from sqlalchemy.orm import Mapped, mapped_column + +from models.base import Base + + +def _utcnow() -> datetime: + return datetime.now(timezone.utc) + + +class User(Base): + """A registered newzy account. + + ``password_hash`` stores ``"$"`` (see + ``core.auth.hash_password``) — never the plaintext password. + """ + + __tablename__ = "users" + + id: Mapped[int] = mapped_column(primary_key=True) + username: Mapped[str] = mapped_column(String(60), unique=True, index=True) + password_hash: Mapped[str] = mapped_column(String(128)) + created_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), default=_utcnow, nullable=False + ) + + def __repr__(self) -> str: # pragma: no cover + return f"" diff --git a/backend/requirements.txt b/backend/requirements.txt index 95f72d1..a9310c8 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -8,6 +8,9 @@ SQLAlchemy>=2.0.41 # --- Schemas / validation --------------------------------------------------- pydantic>=2.11 +# --- Auth (JWT; password hashing uses stdlib hashlib/secrets) -------------- +PyJWT>=2.8 + # --- Misc runtime ----------------------------------------------------------- python-multipart>=0.0.20 diff --git a/backend/schemas/__init__.py b/backend/schemas/__init__.py index 625093a..a84d6da 100644 --- a/backend/schemas/__init__.py +++ b/backend/schemas/__init__.py @@ -1,6 +1,7 @@ """Pydantic request/response schemas for newzy.""" from schemas.article import ArticleBase, ArticleCreate, ArticleRead, ArticleUpdate +from schemas.auth import LoginIn, RegisterIn, TokenOut, UserOut from schemas.author import AuthorBase, AuthorCreate, AuthorRead, AuthorUpdate from schemas.category import CategoryBase, CategoryCreate, CategoryRead, CategoryUpdate from schemas.common import ErrorDetail, HealthResponse, VersionResponse @@ -20,5 +21,9 @@ __all__ = [ "CategoryUpdate", "ErrorDetail", "HealthResponse", + "LoginIn", + "RegisterIn", + "TokenOut", + "UserOut", "VersionResponse", ] diff --git a/backend/schemas/auth.py b/backend/schemas/auth.py new file mode 100644 index 0000000..7f91c98 --- /dev/null +++ b/backend/schemas/auth.py @@ -0,0 +1,39 @@ +"""Authentication request/response schemas (see ``api.v1.auth``).""" + +from pydantic import BaseModel, Field + + +class RegisterIn(BaseModel): + """Payload of ``POST /api/v1/auth/register``. + + Usernames are restricted to 3-20 characters of letters, numbers and + underscores; passwords must be at least 8 characters. + """ + + username: str = Field( + min_length=3, + max_length=20, + pattern=r"^[a-zA-Z0-9_]{3,20}$", + description="3-20 characters: letters, numbers, underscores.", + ) + password: str = Field(min_length=8, max_length=200) + + +class LoginIn(BaseModel): + """Payload of ``POST /api/v1/auth/login``.""" + + username: str = Field(min_length=1, max_length=60) + password: str = Field(min_length=1, max_length=200) + + +class TokenOut(BaseModel): + """Token response shared by the register and login endpoints.""" + + token: str + username: str + + +class UserOut(BaseModel): + """Payload of ``GET /api/v1/auth/me``.""" + + username: str diff --git a/backend/tests/test_auth.py b/backend/tests/test_auth.py new file mode 100644 index 0000000..662cfbf --- /dev/null +++ b/backend/tests/test_auth.py @@ -0,0 +1,198 @@ +"""Tests for the auth primitives (core.auth) and the /api/v1/auth endpoints.""" + +import re +import time + +import jwt as pyjwt +import pytest + +from core import auth +from models import User + + +class TestPasswordHashing: + def test_hash_format_and_roundtrip(self) -> None: + hashed = auth.hash_password("s3cret!") + salt, digest = hashed.split("$", 1) + # salt = secrets.token_hex(16) -> 32 hex chars; sha256 digest -> 64. + assert re.fullmatch(r"[0-9a-f]{32}", salt) + assert re.fullmatch(r"[0-9a-f]{64}", digest) + assert auth.verify_password("s3cret!", hashed) + + def test_unique_salt_per_hash(self) -> None: + assert auth.hash_password("same-password") != auth.hash_password("same-password") + + def test_verify_wrong_password(self) -> None: + hashed = auth.hash_password("correct-horse") + assert not auth.verify_password("wrong-password", hashed) + + def test_verify_rejects_malformed_stored_values(self) -> None: + assert not auth.verify_password("x", "no-salt-separator") + assert not auth.verify_password("x", "zz-!$deadbeef") # non-hex salt + assert not auth.verify_password("x", "") + assert not auth.verify_password("x", "validhex$") # empty digest + + def test_iteration_count_is_owasp_minimum(self) -> None: + assert auth.PBKDF2_ITERATIONS >= 120_000 + + +class TestTokenCreation: + def test_payload_and_seven_day_expiry(self) -> None: + token = auth.create_token("alice") + payload = pyjwt.decode(token, auth.SECRET_KEY, algorithms=["HS256"]) + assert payload["sub"] == "alice" + assert auth.TOKEN_TTL_SECONDS == 7 * 24 * 60 * 60 + assert payload["exp"] == payload["iat"] + auth.TOKEN_TTL_SECONDS + assert payload["exp"] > int(time.time()) + + def test_token_signed_with_wrong_key_fails(self) -> None: + token = auth.create_token("alice") + with pytest.raises(pyjwt.InvalidSignatureError): + pyjwt.decode(token, "some-other-secret", algorithms=["HS256"]) + + +def _register(client, username: str = "alice", password: str = "password123"): + return client.post( + "/api/v1/auth/register", json={"username": username, "password": password} + ) + + +class TestRegisterEndpoint: + def test_register_creates_user_and_returns_token(self, client, session) -> None: + response = _register(client) + assert response.status_code == 201 + body = response.json() + assert body["username"] == "alice" + assert body["token"] + + # The token decodes to the registered username. + payload = pyjwt.decode(body["token"], auth.SECRET_KEY, algorithms=["HS256"]) + assert payload["sub"] == "alice" + + # The user is persisted with a hashed (not plaintext) password. + user = session.query(User).filter(User.username == "alice").first() + assert user is not None + assert user.password_hash != "password123" + assert "$" in user.password_hash + assert auth.verify_password("password123", user.password_hash) + assert user.created_at is not None + + def test_register_duplicate_username_returns_400(self, client) -> None: + assert _register(client).status_code == 201 + response = _register(client) + assert response.status_code == 400 + assert response.json()["code"] == "bad_request" + assert response.json()["detail"] == "Username already exists" + + @pytest.mark.parametrize( + "username", + ["", "ab", "a" * 21, "bad name", "semi;colon", "with-dash", "dot.name", "ünicode"], + ) + def test_register_rejects_invalid_usernames(self, client, username: str) -> None: + assert _register(client, username=username).status_code == 422 + + def test_register_rejects_short_password(self, client) -> None: + response = client.post( + "/api/v1/auth/register", json={"username": "alice", "password": "short"} + ) + assert response.status_code == 422 + + def test_register_requires_both_fields(self, client) -> None: + response = client.post("/api/v1/auth/register", json={"username": "alice"}) + assert response.status_code == 422 + + +class TestLoginEndpoint: + def test_login_success_returns_token(self, client) -> None: + assert _register(client).status_code == 201 + response = client.post( + "/api/v1/auth/login", json={"username": "alice", "password": "password123"} + ) + assert response.status_code == 200 + body = response.json() + assert body["username"] == "alice" + payload = pyjwt.decode(body["token"], auth.SECRET_KEY, algorithms=["HS256"]) + assert payload["sub"] == "alice" + + def test_login_wrong_password_returns_401(self, client) -> None: + _register(client) + response = client.post( + "/api/v1/auth/login", json={"username": "alice", "password": "nope-nope"} + ) + assert response.status_code == 401 + assert response.json()["code"] == "unauthorized" + + def test_login_unknown_user_returns_401(self, client) -> None: + response = client.post( + "/api/v1/auth/login", json={"username": "ghost", "password": "password123"} + ) + assert response.status_code == 401 + + +def _auth_headers(client, username: str = "alice") -> dict: + token = _register(client, username=username).json()["token"] + return {"Authorization": f"Bearer {token}"} + + +class TestMeEndpoint: + def test_me_with_valid_token(self, client) -> None: + response = client.get("/api/v1/auth/me", headers=_auth_headers(client)) + assert response.status_code == 200 + assert response.json() == {"username": "alice"} + + def test_me_without_token_returns_401(self, client) -> None: + response = client.get("/api/v1/auth/me") + assert response.status_code == 401 + assert response.json()["code"] == "unauthorized" + + def test_me_with_garbage_token_returns_401(self, client) -> None: + response = client.get( + "/api/v1/auth/me", headers={"Authorization": "Bearer not.a.jwt"} + ) + assert response.status_code == 401 + + def test_me_with_expired_token_returns_401(self, client) -> None: + _register(client) + now = int(time.time()) + token = pyjwt.encode( + {"sub": "alice", "iat": now - 10, "exp": now - 5}, + auth.SECRET_KEY, + algorithm="HS256", + ) + response = client.get( + "/api/v1/auth/me", headers={"Authorization": f"Bearer {token}"} + ) + assert response.status_code == 401 + + def test_me_with_wrong_secret_returns_401(self, client) -> None: + _register(client) + now = int(time.time()) + token = pyjwt.encode( + {"sub": "alice", "iat": now, "exp": now + 3600}, + "some-other-secret", + algorithm="HS256", + ) + response = client.get( + "/api/v1/auth/me", headers={"Authorization": f"Bearer {token}"} + ) + assert response.status_code == 401 + + def test_me_token_for_deleted_user_returns_401(self, client, session) -> None: + headers = _auth_headers(client) + user = session.query(User).filter(User.username == "alice").first() + assert user is not None + session.delete(user) + session.commit() + response = client.get("/api/v1/auth/me", headers=headers) + assert response.status_code == 401 + + +class TestLogoutEndpoint: + def test_logout_with_valid_token_returns_204(self, client) -> None: + response = client.post("/api/v1/auth/logout", headers=_auth_headers(client)) + assert response.status_code == 204 + assert response.content == b"" + + def test_logout_without_token_returns_401(self, client) -> None: + response = client.post("/api/v1/auth/logout") + assert response.status_code == 401 diff --git a/backend/tests/test_models.py b/backend/tests/test_models.py index cbd841f..b1a6f31 100644 --- a/backend/tests/test_models.py +++ b/backend/tests/test_models.py @@ -3,7 +3,7 @@ import pytest from sqlalchemy.exc import IntegrityError -from models import Article, Author, Category, slugify +from models import Article, Author, Category, User, slugify class TestAuthor: @@ -41,6 +41,25 @@ class TestAuthor: assert author.bio is None +class TestUser: + def test_create_and_commit(self, session) -> None: + user = User(username="alice", password_hash="abc$def") + session.add(user) + session.commit() + session.refresh(user) + assert user.id is not None + assert user.created_at is not None + assert session.get(User, user.id).username == "alice" + + def test_unique_username_enforced(self, session) -> None: + session.add(User(username="alice", password_hash="abc$def")) + session.commit() + session.add(User(username="alice", password_hash="other$hash")) + with pytest.raises(IntegrityError): + session.commit() + session.rollback() + + class TestCategory: def test_create_and_commit(self, session) -> None: category = Category(name="Technology", slug="technology") diff --git a/data/.gitignore b/data/.gitignore index dcb4d7a..0999efe 100644 --- a/data/.gitignore +++ b/data/.gitignore @@ -1,6 +1,9 @@ # Exclude everything under data/ from version control (SQLite database, # uploads, ...) except the keep file below, so the directory structure # (data/db/) survives a fresh clone. +# +# This blanket rule also covers the database files required by the M5 +# milestone: *.db, *.sqlite, data.db, newzy.db (e.g. data/db/newzy.db). * !.gitignore !keep_files.txt diff --git a/docker-compose.yml b/docker-compose.yml index 070df26..c4faa66 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -25,6 +25,9 @@ services: - DATABASE_URL=sqlite:///./data/db/newzy.db - DEBUG=false - BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:5173 + # JWT signing key (override in .env; the backend falls back to a dev + # default when unset). Never use the dev default in production. + - HN_SECRET_KEY=${HN_SECRET_KEY:-newzy-dev-secret-change-me} healthcheck: test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] interval: 30s diff --git a/frontend/playwright/e2e/auth.spec.ts b/frontend/playwright/e2e/auth.spec.ts new file mode 100644 index 0000000..6d48bcc --- /dev/null +++ b/frontend/playwright/e2e/auth.spec.ts @@ -0,0 +1,198 @@ +import { expect, test, type Page } from '@playwright/test'; + +const TOKEN = 'mock-jwt-token'; + +const envelope = (detail: string, code: string) => JSON.stringify({ detail, code }); + +/** + * Mock the auth API so the flows do not depend on a running backend + * (same approach as api.spec.ts). The "server" accepts: + * - register: any username except `taken`, any password + * - login: alice / password123 + * - me: the mock token -> user `alice` + */ +function mockAuthApi(page: Page): void { + page.route('**/api/v1/auth/register', (route) => { + const body = route.request().postDataJSON(); + if (body.username === 'taken') { + return route.fulfill({ + status: 400, + contentType: 'application/json', + body: envelope('Username already exists', 'bad_request'), + }); + } + return route.fulfill({ + status: 201, + contentType: 'application/json', + body: JSON.stringify({ token: TOKEN, username: body.username }), + }); + }); + + page.route('**/api/v1/auth/login', (route) => { + const body = route.request().postDataJSON(); + if (body.username !== 'alice' || body.password !== 'password123') { + return route.fulfill({ + status: 401, + contentType: 'application/json', + body: envelope('Invalid username or password', 'unauthorized'), + }); + } + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ token: TOKEN, username: body.username }), + }); + }); + + page.route('**/api/v1/auth/me', (route) => { + const header = route.request().headers()['authorization']; + if (header !== `Bearer ${TOKEN}`) { + return route.fulfill({ + status: 401, + contentType: 'application/json', + body: envelope('Invalid or expired token', 'unauthorized'), + }); + } + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ username: 'alice' }), + }); + }); + + page.route('**/api/v1/auth/logout', (route) => route.fulfill({ status: 204 })); +} + +/** Store a session token before the app boots (session-restore tests). */ +async function seedToken(page: Page, token: string): Promise { + await page.addInitScript((value) => localStorage.setItem('AUTH_TOKEN', value), token); +} + +const readToken = (page: Page) => page.evaluate(() => localStorage.getItem('AUTH_TOKEN')); + +const accountNav = (page: Page) => page.getByRole('navigation', { name: 'Account' }); + +test.describe('auth flows', () => { + test('register: creates an account, stores the token and signs the user in', async ({ + page, + }) => { + mockAuthApi(page); + + await page.goto('/register'); + await page.getByLabel('Username').fill('newuser'); + await page.getByLabel('Password', { exact: true }).fill('password123'); + await page.getByLabel('Confirm password').fill('password123'); + await page.getByRole('button', { name: /register/i }).click(); + + // Registration auto-signs in and redirects to home. + await expect(page).toHaveURL('/'); + expect(await readToken(page)).toBe(TOKEN); + await expect(accountNav(page).getByText('newuser')).toBeVisible(); + await expect(accountNav(page).getByRole('link', { name: /sign out/i })).toBeVisible(); + }); + + test('register: rejects a duplicate username with the backend error', async ({ page }) => { + mockAuthApi(page); + + await page.goto('/register'); + await page.getByLabel('Username').fill('taken'); + await page.getByLabel('Password', { exact: true }).fill('password123'); + await page.getByLabel('Confirm password').fill('password123'); + await page.getByRole('button', { name: /register/i }).click(); + + await expect(page.getByRole('alert')).toContainText('Username already exists'); + expect(await readToken(page)).toBeNull(); + await expect(page).toHaveURL('/register'); + }); + + test('register: validates mismatched passwords client-side', async ({ page }) => { + mockAuthApi(page); + + await page.goto('/register'); + await page.getByLabel('Username').fill('newuser'); + await page.getByLabel('Password', { exact: true }).fill('password123'); + await page.getByLabel('Confirm password').fill('different123'); + await page.getByRole('button', { name: /register/i }).click(); + + await expect(page.getByRole('alert')).toContainText('Passwords do not match.'); + expect(await readToken(page)).toBeNull(); + }); + + test('login: stores the token and signs the user in', async ({ page }) => { + mockAuthApi(page); + + await page.goto('/login'); + await page.getByLabel('Username').fill('alice'); + await page.getByLabel('Password').fill('password123'); + await page.getByRole('button', { name: /sign in/i }).click(); + + await expect(page).toHaveURL('/'); + expect(await readToken(page)).toBe(TOKEN); + await expect(accountNav(page).getByText('alice')).toBeVisible(); + }); + + test('login: shows the backend error for invalid credentials', async ({ page }) => { + mockAuthApi(page); + + await page.goto('/login'); + await page.getByLabel('Username').fill('alice'); + await page.getByLabel('Password').fill('wrong-password'); + await page.getByRole('button', { name: /sign in/i }).click(); + + await expect(page.getByRole('alert')).toContainText('Invalid username or password'); + expect(await readToken(page)).toBeNull(); + await expect(page).toHaveURL('/login'); + }); + + test('restores the session from a stored token on page load', async ({ page }) => { + mockAuthApi(page); + await seedToken(page, TOKEN); + + await page.goto('/'); + + await expect(accountNav(page).getByText('alice')).toBeVisible(); + expect(await readToken(page)).toBe(TOKEN); + }); + + test('clears an invalid stored token on page load', async ({ page }) => { + mockAuthApi(page); + await seedToken(page, 'expired-or-forged-token'); + + await page.goto('/'); + + // Restore failed -> signed-out header, token removed. + await expect(accountNav(page).getByRole('link', { name: 'Sign in' })).toBeVisible(); + expect(await readToken(page)).toBeNull(); + }); + + test('redirects unauthenticated users from /account to /login', async ({ page }) => { + mockAuthApi(page); + + await page.goto('/account'); + + await expect(page).toHaveURL('/login'); + }); + + test('renders the protected /account page for a signed-in user', async ({ page }) => { + mockAuthApi(page); + await seedToken(page, TOKEN); + + await page.goto('/account'); + + await expect(page.getByTestId('account-page')).toBeVisible(); + await expect(page.getByRole('heading', { level: 1, name: 'Account' })).toBeVisible(); + await expect(page.getByTestId('account-page').getByText('alice')).toBeVisible(); + }); + + test('sign out clears the token and returns to the login page', async ({ page }) => { + mockAuthApi(page); + await seedToken(page, TOKEN); + + await page.goto('/'); + await accountNav(page).getByRole('link', { name: /sign out/i }).click(); + + await expect(page).toHaveURL('/login'); + expect(await readToken(page)).toBeNull(); + await expect(page.getByRole('status').getByText(/signed out/i)).toBeVisible(); + }); +}); diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 587676d..6221348 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,8 +1,13 @@ import { BrowserRouter, Link, Route, Routes } from 'react-router-dom'; +import { AuthProvider, RequireAuth } from './auth'; import Layout from './components/ui/Layout'; +import Account from './pages/Account'; import ArticlePage from './pages/ArticlePage'; import CategoriesPage from './pages/CategoriesPage'; import Home from './pages/Home'; +import Login from './pages/Login'; +import Register from './pages/Register'; +import SignOut from './pages/SignOut'; /** 404 fallback for unknown routes. */ function NotFound() { @@ -20,11 +25,13 @@ function NotFound() { } /** - * Root component: owns the React Router setup. + * Root component: owns the React Router + auth setup. * - * BrowserRouter wraps the whole app; Layout provides the shared shell - * (header/footer); Routes maps URLs to page components in src/pages/. - * In-app navigation always uses react-router-dom /. + * BrowserRouter wraps the whole app; AuthProvider restores the JWT + * session and exposes login/register/logout (see src/auth.tsx); Layout + * provides the shared shell (header/footer); Routes maps URLs to page + * components in src/pages/. In-app navigation always uses + * react-router-dom /. */ export default function App() { return ( @@ -34,15 +41,28 @@ export default function App() { v7_relativeSplatPath: true, }} > - - - } /> - } /> - } /> - } /> - } /> - - + + + + } /> + } /> + } /> + } /> + } /> + } /> + } /> + + + + } + /> + } /> + + + ); } diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index cf350b5..144cae4 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -16,10 +16,14 @@ import type { HealthResponse, VersionResponse, } from '../types'; +import type { MeResponse, TokenResponse } from '../types/auth'; export const API_BASE_URL: string = (import.meta.env.VITE_API_BASE_URL as string | undefined) ?? '/api/v1'; +/** localStorage key under which the JWT session token is persisted. */ +export const TOKEN_KEY = 'AUTH_TOKEN'; + /** Error thrown for failed API requests (network or non-2xx responses). */ export class ApiError extends Error { readonly status: number; @@ -36,6 +40,8 @@ export class ApiError extends Error { interface RequestOptions extends Omit { /** JSON-serializable request body (stringified automatically). */ body?: unknown; + /** Use this Bearer token instead of the one stored under TOKEN_KEY. */ + token?: string; } /** @@ -43,15 +49,19 @@ interface RequestOptions extends Omit { * response and converts failures into `ApiError`. */ async function request(path: string, options: RequestOptions = {}): Promise { - const { body, headers, ...rest } = options; + const { body, headers, token, ...rest } = options; let response: Response; try { + // Attach the JWT (explicit override or the stored session) so the + // backend can identify the caller on protected endpoints. + const bearer = token ?? localStorage.getItem(TOKEN_KEY); response = await fetch(`${API_BASE_URL}${path}`, { ...rest, headers: { Accept: 'application/json', ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}), + ...(bearer ? { Authorization: `Bearer ${bearer}` } : {}), ...headers, }, body: body !== undefined ? JSON.stringify(body) : undefined, @@ -61,6 +71,9 @@ async function request(path: string, options: RequestOptions = {}): Promise { return api.get('/version'); } +/* --- Auth endpoints (JWT sessions, see `src/auth.tsx`) ------------------- */ + +/** `POST /api/v1/auth/register` — create an account; returns the JWT. */ +export function register(username: string, password: string): Promise { + return api.post('/auth/register', { username, password }); +} + +/** `POST /api/v1/auth/login` — authenticate; returns the JWT. */ +export function login(username: string, password: string): Promise { + return api.post('/auth/login', { username, password }); +} + +/** `GET /api/v1/auth/me` — current user for the explicit (or stored) token. */ +export function me(token?: string): Promise { + return api.get('/auth/me', token !== undefined ? { token } : undefined); +} + +/** `POST /api/v1/auth/logout` — stateless; the client discards the token. */ +export function logout(): Promise { + return api.post('/auth/logout', undefined); +} + /** * `GET /api/v1/articles` — list of published articles. * diff --git a/frontend/src/assets/styles/globals.css b/frontend/src/assets/styles/globals.css index 5bd5734..3a0fcf0 100644 --- a/frontend/src/assets/styles/globals.css +++ b/frontend/src/assets/styles/globals.css @@ -31,4 +31,49 @@ .btn-secondary { @apply inline-flex items-center justify-center gap-2 rounded-md border border-slate-300 bg-white px-4 py-2 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50; } + + /* --- Auth pages (login / register / sign out) ------------------------- */ + + /* Centered wrapper so auth cards sit in the middle of the viewport. */ + .auth-wrap { + @apply flex min-h-[60vh] items-center justify-center px-4 py-12; + } + + /* Card holding an auth form. */ + .auth-card { + @apply w-full max-w-sm rounded-xl border border-slate-200 bg-white p-6 shadow-sm; + } + + /* Auth card heading (icon + label). */ + .auth-title { + @apply mb-4 flex items-center gap-2 text-lg font-semibold text-slate-900; + } + + /* Form field: label stacked above its input. */ + .field { + @apply mb-4; + } + + .field label { + @apply mb-1 block text-sm font-medium text-slate-700; + } + + /* Text input used by the auth forms. */ + .input { + @apply w-full rounded-md border border-slate-300 px-3 py-2 text-sm text-slate-900 placeholder:text-slate-400 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/40; + } + + /* Inline error/success notices inside auth cards. */ + .auth-error { + @apply mb-3 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700; + } + + .auth-success { + @apply mb-3 rounded-md border border-green-200 bg-green-50 px-3 py-2 text-sm text-green-700; + } + + /* Cross-link line at the bottom of an auth card. */ + .auth-alt { + @apply mt-4 text-center text-sm text-slate-600; + } } diff --git a/frontend/src/auth.tsx b/frontend/src/auth.tsx new file mode 100644 index 0000000..139ad2a --- /dev/null +++ b/frontend/src/auth.tsx @@ -0,0 +1,116 @@ +/** + * Authentication state for the app. + * + * - `AuthProvider` restores the session on load (validates the token + * stored under `AUTH_TOKEN` against `GET /api/v1/auth/me`, drops it + * when invalid/expired) and exposes `login` / `register` / `logout`. + * - The JWT is attached to every API request automatically (see + * `api/client.ts`); this module only owns the username + ready state. + */ +import { + ReactNode, + createContext, + useCallback, + useContext, + useEffect, + useMemo, + useState, +} from 'react'; +import { Navigate, useLocation } from 'react-router-dom'; +import { + TOKEN_KEY, + login as apiLogin, + logout as apiLogout, + me as apiMe, + register as apiRegister, +} from './api/client'; + +export interface AuthState { + /** Logged-in username, or `null` when signed out. */ + username: string | null; + /** `false` until the initial session-restore attempt has finished. */ + ready: boolean; + /** Authenticate; stores the returned JWT and signs the user in. */ + login: (username: string, password: string) => Promise; + /** Register a new account; stores the returned JWT and signs in. */ + register: (username: string, password: string) => Promise; + /** Clear the stored token (best-effort server call) and sign out. */ + logout: () => void; +} + +const AuthContext = createContext(null); + +export function AuthProvider({ children }: { children: ReactNode }) { + const [username, setUsername] = useState(null); + const [ready, setReady] = useState(false); + + // Restore the session on first load: validate the stored token and drop + // it when the backend rejects it (expired, invalid or unknown user). + useEffect(() => { + const stored = localStorage.getItem(TOKEN_KEY); + if (!stored) { + setReady(true); + return; + } + apiMe(stored) + .then((user) => setUsername(user.username)) + .catch(() => localStorage.removeItem(TOKEN_KEY)) + .finally(() => setReady(true)); + }, []); + + const login = useCallback(async (name: string, password: string) => { + const res = await apiLogin(name, password); + localStorage.setItem(TOKEN_KEY, res.token); + setUsername(res.username); + }, []); + + const register = useCallback(async (name: string, password: string) => { + const res = await apiRegister(name, password); + localStorage.setItem(TOKEN_KEY, res.token); + setUsername(res.username); + }, []); + + const logout = useCallback(() => { + // Best effort: the token is discarded client-side regardless of + // whether the (stateless) server endpoint is reachable. + apiLogout().catch(() => undefined); + localStorage.removeItem(TOKEN_KEY); + setUsername(null); + }, []); + + const value = useMemo( + () => ({ username, ready, login, register, logout }), + [username, ready, login, register, logout], + ); + + return {children}; +} + +export function useAuth(): AuthState { + const ctx = useContext(AuthContext); + if (!ctx) throw new Error('useAuth must be used within '); + return ctx; +} + +/** + * Route guard for authenticated users: shows a brief loading state while + * the session is being restored, redirects to `/login` (remembering the + * intended path in router state) when signed out, and renders `children` + * otherwise. + */ +export function RequireAuth({ children }: { children: ReactNode }) { + const { username, ready } = useAuth(); + const location = useLocation(); + + if (!ready) { + return ( +
+ Checking session… +
+ ); + } + if (username === null) { + return ; + } + return <>{children}; +} diff --git a/frontend/src/components/ui/Header.tsx b/frontend/src/components/ui/Header.tsx index 3333a02..a28e25c 100644 --- a/frontend/src/components/ui/Header.tsx +++ b/frontend/src/components/ui/Header.tsx @@ -1,6 +1,7 @@ -import { FileText, Home, Menu, Settings, X, type LucideIcon } from 'lucide-react'; +import { FileText, Home, LogOut, Menu, Settings, User, X, type LucideIcon } from 'lucide-react'; import { useState } from 'react'; -import { NavLink } from 'react-router-dom'; +import { Link, NavLink } from 'react-router-dom'; +import { useAuth } from '../../auth'; import logo from '../../assets/logo.svg'; import { cn } from '../../lib/utils'; @@ -31,6 +32,7 @@ const NAV_ITEMS: NavItem[] = [ */ export function Header({ className }: HeaderProps) { const [menuOpen, setMenuOpen] = useState(false); + const { username, ready } = useAuth(); const closeMenu = () => setMenuOpen(false); @@ -41,6 +43,35 @@ export function Header({ className }: HeaderProps) { isActive && 'bg-blue-50 text-blue-700 hover:bg-blue-100 hover:text-blue-800', ); + const plainLinkClasses = + 'inline-flex items-center gap-2 rounded-md px-3 py-2 text-sm font-medium text-slate-600 hover:bg-slate-100 hover:text-slate-900'; + + // Auth links: sign-in/register when logged out, account/sign-out when + // signed in (rendered once the session restore has settled). + const renderAuthLinks = (onClick?: () => void) => + ready && + (username ? ( + <> + + + +