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.
This commit is contained in:
Daniel Samson committed 2026-10-30 17:03:00 +00:00
1 parent ed7b30438e
commit b186d0f797
35 files changed
+2422 -36

No files matched your search

+4
View File
@@ -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
+4
View File
@@ -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:
+70
View File
@@ -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)
+6
View File
@@ -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:
+97
View File
@@ -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 <token>`` 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 ``"<salt>$<digest>"`` 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 ``"<salt>$<digest>"`` 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
+2 -1
View File
@@ -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"]
+34
View File
@@ -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 ``"<salt>$<pbkdf2-digest>"`` (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"<User id={self.id} username={self.username!r}>"
+3
View File
@@ -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
+5
View File
@@ -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",
]
+39
View File
@@ -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
+198
View File
@@ -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
+20 -1
View File
@@ -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")