Files
newz-qwen-27b/backend
Daniel Samson b186d0f797 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.
2026-10-30 17:03:00 +00:00
..

newzy — Backend

FastAPI backend for the newzy news web application. This milestone (M2) provides the API backbone: application factory, SQLite persistence via SQLAlchemy, core ORM models (Article, Author, Category), Pydantic schemas, standardized error handling, and a unit-tested, containerized deployment path.

Project structure

backend/
├── api/
│   └── v1/
│       └── __init__.py     # /api/v1 routes (health, version)
├── core/
│   ├── __init__.py         # re-exports create_app
│   └── app.py              # app factory, CORS, global error handlers
├── db/
│   ├── __init__.py
│   └── session.py          # engine, session factory, get_db dependency
├── models/
│   ├── __init__.py
│   ├── base.py             # declarative Base
│   ├── article.py          # Article model
│   ├── author.py           # Author model
│   └── category.py         # Category model + slugify()
├── schemas/
│   ├── __init__.py
│   ├── article.py          # Article request/response schemas
│   ├── author.py           # Author request/response schemas
│   ├── category.py         # Category request/response schemas
│   └── common.py           # Health/Version payloads, ErrorDetail envelope
├── tests/
│   ├── conftest.py         # fixtures: per-test SQLite DB + TestClient
│   ├── test_health.py
│   ├── test_version.py
│   └── test_models.py
├── main.py                 # application entry point (uvicorn target)
├── config.py               # env-driven settings (DATABASE_URL, CORS_ORIGINS)
├── requirements.txt
├── Dockerfile
├── .dockerignore
├── .env.example
├── .gitignore
└── pytest.ini

Getting started

1. Local development

cd backend
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

uvicorn main:app --reload

The server starts on http://localhost:8000. Interactive API docs are served at http://localhost:8000/docs.

The SQLite database file is created automatically at ./data/db/newzy.db (directory included) on first start.

2. With Docker Compose (from the repository root)

docker compose up --build

This builds the image, maps port 8000, and persists the SQLite database in ./data/db on the host.

3. Run the tests

cd backend
pytest

Coverage is reported per module (see pytest.ini). Tests run against a throwaway SQLite file per test — the real database is never touched.

Configuration

All settings come from environment variables (see .env.example):

Variable Default Description
DATABASE_URL sqlite:///./data/db/newzy.db SQLAlchemy database URL
CORS_ORIGINS http://localhost:3000,http://127.0.0.1:3000 Comma-separated allowed origins

Inside the container the database lives at /app/data/db/newzy.db on the mounted volume (see docker-compose.yml at the repository root).

API endpoints

Method Path Description
GET /health Root health check
GET /api/v1/health Health check (versioned alternative path)
GET /api/v1/version Application name and version
GET /docs Interactive OpenAPI documentation (Swagger)
GET /api/v1/openapi.json OpenAPI schema

Examples

Health check:

curl -s http://localhost:8000/health
# {"status":"ok","version":"0.1.0"}

Version:

curl -s http://localhost:8000/api/v1/version
# {"app":"newzy","version":"0.1.0"}

Error format

All non-2xx responses use a standardized envelope:

{
  "detail": "Not Found",
  "code": "not_found"
}

Validation failures (HTTP 422) additionally include per-field errors:

{
  "detail": "Request validation failed.",
  "code": "validation_error",
  "errors": [
    {
      "loc": ["body", "title"],
      "msg": "String should have at least 1 character",
      "type": "string_too_short"
    }
  ]
}
code HTTP Meaning
bad_request 400 Malformed request
unauthorized 401 Missing/invalid credentials
forbidden 403 Insufficient permissions
not_found 404 Resource does not exist
method_not_allowed 405 Method not allowed on resource
conflict 409 State conflict (e.g. duplicate)
validation_error 422 Request failed schema validation
too_many_requests 429 Rate limit exceeded
internal_error 500 Unhandled server error

Data model

Author 1 ──── * Article * ──── 1 Category
  • Article: id, title (unique, ≤200 chars), content, author_id (FK), category_id (FK), created_at, published (default false)
  • Author: id, name (unique, ≤100 chars), email (unique, ≤255 chars), bio (nullable)
  • Category: id, name (unique, ≤100 chars), slug (unique, ≤100 chars)

ORM relationships are defined on both sides (author.articles, category.articles, article.author, article.category), and SQLite foreign key enforcement is enabled via a PRAGMA foreign_keys=ON connection listener.

Docker

The Dockerfile builds on python:3.11-slim, installs requirements.txt, copies the application code, exposes port 8000, and runs uvicorn main:app --host 0.0.0.0 --port 8000.

docker build -t newzy-backend ./backend
docker run --rm -p 8000:8000 -v $(pwd)/data/db:/app/data/db \
  -e DATABASE_URL=sqlite:///./data/db/newzy.db newzy-backend

Notes & limitations

  • SQLite is fine for development and demos; a production database (e.g. Postgres) will be configured in a later milestone.
  • No authentication, rate limiting, or pagination yet — those arrive with the article CRUD milestones.
  • CORS origins are configured for frontend development; validate them before production deployment.