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:
1 parent
ed7b30438e
commit
b186d0f797
35 files changed
+2422
-36
No files matched your search
@@ -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.
|
||||
|
||||
@@ -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
|
||||
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
@@ -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"]
|
||||
@@ -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}>"
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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")
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -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<void> {
|
||||
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();
|
||||
});
|
||||
});
|
||||
+33
-13
@@ -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 <Link>/<NavLink>.
|
||||
* 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 <Link>/<NavLink>.
|
||||
*/
|
||||
export default function App() {
|
||||
return (
|
||||
@@ -34,15 +41,28 @@ export default function App() {
|
||||
v7_relativeSplatPath: true,
|
||||
}}
|
||||
>
|
||||
<Layout>
|
||||
<Routes>
|
||||
<Route path="/" element={<Home />} />
|
||||
<Route path="/articles" element={<ArticlePage />} />
|
||||
<Route path="/articles/:id" element={<ArticlePage />} />
|
||||
<Route path="/categories" element={<CategoriesPage />} />
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
</Layout>
|
||||
<AuthProvider>
|
||||
<Layout>
|
||||
<Routes>
|
||||
<Route path="/" element={<Home />} />
|
||||
<Route path="/articles" element={<ArticlePage />} />
|
||||
<Route path="/articles/:id" element={<ArticlePage />} />
|
||||
<Route path="/categories" element={<CategoriesPage />} />
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/register" element={<Register />} />
|
||||
<Route path="/sign-out" element={<SignOut />} />
|
||||
<Route
|
||||
path="/account"
|
||||
element={
|
||||
<RequireAuth>
|
||||
<Account />
|
||||
</RequireAuth>
|
||||
}
|
||||
/>
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
</Layout>
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
);
|
||||
}
|
||||
@@ -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<RequestInit, 'body'> {
|
||||
/** 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<RequestInit, 'body'> {
|
||||
* response and converts failures into `ApiError`.
|
||||
*/
|
||||
async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
|
||||
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<T>(path: string, options: RequestOptions = {}): Promise<T
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
// 401: the stored session is invalid/expired — drop it so the UI can
|
||||
// redirect to login instead of retrying with a dead token.
|
||||
if (response.status === 401) localStorage.removeItem(TOKEN_KEY);
|
||||
let payload: ApiErrorPayload | null = null;
|
||||
try {
|
||||
payload = (await response.json()) as ApiErrorPayload;
|
||||
@@ -159,6 +172,28 @@ export function getVersion(): Promise<VersionResponse> {
|
||||
return api.get<VersionResponse>('/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<TokenResponse> {
|
||||
return api.post<TokenResponse>('/auth/register', { username, password });
|
||||
}
|
||||
|
||||
/** `POST /api/v1/auth/login` — authenticate; returns the JWT. */
|
||||
export function login(username: string, password: string): Promise<TokenResponse> {
|
||||
return api.post<TokenResponse>('/auth/login', { username, password });
|
||||
}
|
||||
|
||||
/** `GET /api/v1/auth/me` — current user for the explicit (or stored) token. */
|
||||
export function me(token?: string): Promise<MeResponse> {
|
||||
return api.get<MeResponse>('/auth/me', token !== undefined ? { token } : undefined);
|
||||
}
|
||||
|
||||
/** `POST /api/v1/auth/logout` — stateless; the client discards the token. */
|
||||
export function logout(): Promise<void> {
|
||||
return api.post<void>('/auth/logout', undefined);
|
||||
}
|
||||
|
||||
/**
|
||||
* `GET /api/v1/articles` — list of published articles.
|
||||
*
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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<void>;
|
||||
/** Register a new account; stores the returned JWT and signs in. */
|
||||
register: (username: string, password: string) => Promise<void>;
|
||||
/** Clear the stored token (best-effort server call) and sign out. */
|
||||
logout: () => void;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthState | null>(null);
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [username, setUsername] = useState<string | null>(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 <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
||||
}
|
||||
|
||||
export function useAuth(): AuthState {
|
||||
const ctx = useContext(AuthContext);
|
||||
if (!ctx) throw new Error('useAuth must be used within <AuthProvider>');
|
||||
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 (
|
||||
<div className="container-page flex justify-center py-16" role="status">
|
||||
<span className="animate-pulse text-sm text-slate-500">Checking session…</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (username === null) {
|
||||
return <Navigate to="/login" replace state={{ from: location.pathname }} />;
|
||||
}
|
||||
return <>{children}</>;
|
||||
}
|
||||
@@ -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 ? (
|
||||
<>
|
||||
<NavLink to="/account" className={linkClasses} onClick={onClick}>
|
||||
<User className="h-5 w-5" aria-hidden="true" />
|
||||
<span>{username}</span>
|
||||
</NavLink>
|
||||
<Link to="/sign-out" className={plainLinkClasses} onClick={onClick}>
|
||||
<LogOut className="h-5 w-5" aria-hidden="true" />
|
||||
<span>Sign out</span>
|
||||
</Link>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Link to="/login" className={plainLinkClasses} onClick={onClick}>
|
||||
<span>Sign in</span>
|
||||
</Link>
|
||||
<Link to="/register" className="btn !px-3 !py-2" onClick={onClick}>
|
||||
<span>Register</span>
|
||||
</Link>
|
||||
</>
|
||||
));
|
||||
|
||||
const renderNav = (id: string, itemClasses?: string) => (
|
||||
<nav id={id} aria-label={`${id === 'mobile-menu' ? 'Mobile' : 'Main'} navigation`} className={itemClasses}>
|
||||
{NAV_ITEMS.map(({ to, label, icon: Icon, end }) => (
|
||||
@@ -73,6 +104,11 @@ export function Header({ className }: HeaderProps) {
|
||||
{/* Desktop navigation */}
|
||||
{renderNav('main-nav', 'hidden items-center gap-1 md:flex')}
|
||||
|
||||
{/* Account (auth) links */}
|
||||
<nav aria-label="Account" className="hidden items-center gap-1 md:flex">
|
||||
{renderAuthLinks()}
|
||||
</nav>
|
||||
|
||||
{/* Mobile menu toggle */}
|
||||
<button
|
||||
type="button"
|
||||
@@ -91,7 +127,14 @@ export function Header({ className }: HeaderProps) {
|
||||
</div>
|
||||
|
||||
{/* Mobile navigation (rendered only while open) */}
|
||||
{menuOpen && renderNav('mobile-menu', 'flex flex-col gap-1 border-t border-slate-200 px-4 pb-4 pt-2 md:hidden')}
|
||||
{menuOpen && (
|
||||
<div className="flex flex-col border-t border-slate-200 px-4 pb-4 pt-2 md:hidden">
|
||||
{renderNav('mobile-menu', 'flex flex-col gap-1')}
|
||||
<div className="mt-1 flex flex-col gap-1 border-t border-slate-200 pt-2">
|
||||
{renderAuthLinks(closeMenu)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { useAuth } from '../auth';
|
||||
|
||||
/**
|
||||
* Placeholder account page (protected by `RequireAuth`): proves the
|
||||
* auth-guarded routing works end-to-end. Real profile features arrive
|
||||
* in a later milestone.
|
||||
*/
|
||||
export default function Account() {
|
||||
const { username } = useAuth();
|
||||
|
||||
return (
|
||||
<div className="container-page" data-testid="account-page">
|
||||
<h1 className="mb-2 text-3xl font-bold text-slate-900">Account</h1>
|
||||
<p className="text-sm text-slate-600">
|
||||
You are signed in as{' '}
|
||||
<strong className="font-semibold text-slate-900">{username}</strong>. Profile
|
||||
settings will live here.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import { FormEvent, useState } from 'react';
|
||||
import { Link, useLocation, useNavigate } from 'react-router-dom';
|
||||
import { Loader2, LogIn } from 'lucide-react';
|
||||
import { useAuth } from '../auth';
|
||||
|
||||
interface LoginLocationState {
|
||||
/** Route the user was trying to reach (set by `RequireAuth`). */
|
||||
from?: string;
|
||||
/** `true` when arriving here right after a sign-out. */
|
||||
signedOut?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Login page: authenticates against `POST /api/v1/auth/login` via
|
||||
* `useAuth` (which stores the JWT) and redirects back to the intended
|
||||
* page, or to home.
|
||||
*/
|
||||
export default function Login() {
|
||||
const { login } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const state = (location.state ?? null) as LoginLocationState | null;
|
||||
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const submit = async (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (!username.trim() || !password) {
|
||||
setError('Please enter both username and password.');
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await login(username.trim(), password);
|
||||
const from = state?.from;
|
||||
navigate(from && from !== '/login' ? from : '/', { replace: true });
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Sign in failed');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="auth-wrap">
|
||||
<div className="auth-card" data-testid="login-card">
|
||||
<h1 className="auth-title">
|
||||
<LogIn size={18} aria-hidden="true" />
|
||||
Sign in
|
||||
</h1>
|
||||
|
||||
{state?.signedOut && (
|
||||
<p className="auth-success" role="status">
|
||||
You have been signed out.
|
||||
</p>
|
||||
)}
|
||||
{error && (
|
||||
<p className="auth-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<form onSubmit={submit}>
|
||||
<div className="field">
|
||||
<label htmlFor="login-username">Username</label>
|
||||
<input
|
||||
id="login-username"
|
||||
className="input"
|
||||
value={username}
|
||||
onChange={(event) => setUsername(event.target.value)}
|
||||
placeholder="your username"
|
||||
maxLength={60}
|
||||
autoComplete="username"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="login-password">Password</label>
|
||||
<input
|
||||
id="login-password"
|
||||
type="password"
|
||||
className="input"
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
placeholder="your password"
|
||||
maxLength={200}
|
||||
autoComplete="current-password"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<button className="btn" type="submit" disabled={busy}>
|
||||
{busy ? (
|
||||
<Loader2 size={15} className="animate-spin" aria-hidden="true" />
|
||||
) : (
|
||||
<LogIn size={15} aria-hidden="true" />
|
||||
)}
|
||||
{busy ? 'Signing in…' : 'Sign in'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<p className="auth-alt">
|
||||
No account yet?{' '}
|
||||
<Link to="/register" className="font-medium text-blue-700 hover:underline">
|
||||
Register
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { FormEvent, useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { Loader2, UserPlus } from 'lucide-react';
|
||||
import { useAuth } from '../auth';
|
||||
|
||||
/** Must match the backend `RegisterIn.username` pattern. */
|
||||
const USERNAME_PATTERN = /^[a-zA-Z0-9_]{3,20}$/;
|
||||
|
||||
/**
|
||||
* Registration page: validates the inputs client-side, then calls
|
||||
* `POST /api/v1/auth/register` via `useAuth` (which stores the JWT and
|
||||
* signs the user in). Backend rejections (e.g. duplicate username) are
|
||||
* shown verbatim.
|
||||
*/
|
||||
export default function Register() {
|
||||
const { register } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [confirm, setConfirm] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const submit = async (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
const name = username.trim();
|
||||
if (!USERNAME_PATTERN.test(name)) {
|
||||
setError('Username must be 3–20 characters: letters, numbers or underscores.');
|
||||
return;
|
||||
}
|
||||
if (password.length < 8) {
|
||||
setError('Password must be at least 8 characters.');
|
||||
return;
|
||||
}
|
||||
if (password !== confirm) {
|
||||
setError('Passwords do not match.');
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await register(name, password);
|
||||
navigate('/', { replace: true });
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Registration failed');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="auth-wrap">
|
||||
<div className="auth-card" data-testid="register-card">
|
||||
<h1 className="auth-title">
|
||||
<UserPlus size={18} aria-hidden="true" />
|
||||
Create an account
|
||||
</h1>
|
||||
|
||||
{error && (
|
||||
<p className="auth-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<form onSubmit={submit}>
|
||||
<div className="field">
|
||||
<label htmlFor="reg-username">Username</label>
|
||||
<input
|
||||
id="reg-username"
|
||||
className="input"
|
||||
value={username}
|
||||
onChange={(event) => setUsername(event.target.value)}
|
||||
placeholder="3–20 letters, numbers or underscores"
|
||||
maxLength={20}
|
||||
autoComplete="username"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="reg-password">Password</label>
|
||||
<input
|
||||
id="reg-password"
|
||||
type="password"
|
||||
className="input"
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
placeholder="at least 8 characters"
|
||||
maxLength={200}
|
||||
minLength={8}
|
||||
autoComplete="new-password"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="reg-confirm">Confirm password</label>
|
||||
<input
|
||||
id="reg-confirm"
|
||||
type="password"
|
||||
className="input"
|
||||
value={confirm}
|
||||
onChange={(event) => setConfirm(event.target.value)}
|
||||
placeholder="repeat the password"
|
||||
maxLength={200}
|
||||
minLength={8}
|
||||
autoComplete="new-password"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<button className="btn" type="submit" disabled={busy}>
|
||||
{busy ? (
|
||||
<Loader2 size={15} className="animate-spin" aria-hidden="true" />
|
||||
) : (
|
||||
<UserPlus size={15} aria-hidden="true" />
|
||||
)}
|
||||
{busy ? 'Creating account…' : 'Register'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<p className="auth-alt">
|
||||
Already have an account?{' '}
|
||||
<Link to="/login" className="font-medium text-blue-700 hover:underline">
|
||||
Sign in
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { LogOut } from 'lucide-react';
|
||||
import { useAuth } from '../auth';
|
||||
|
||||
/**
|
||||
* Sign-out page: clears the stored JWT (best-effort call to the
|
||||
* stateless `POST /api/v1/auth/logout`) and redirects to the login page
|
||||
* with a "signed out" notice.
|
||||
*/
|
||||
export default function SignOut() {
|
||||
const { logout } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
logout();
|
||||
navigate('/login', { replace: true, state: { signedOut: true } });
|
||||
}, [logout, navigate]);
|
||||
|
||||
return (
|
||||
<div className="auth-wrap" role="status">
|
||||
<div className="flex items-center gap-2 text-slate-600">
|
||||
<LogOut size={20} aria-hidden="true" />
|
||||
<span className="text-sm">Signing out…</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,18 +1,33 @@
|
||||
import { fireEvent, screen, within } from '@testing-library/react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { Mock } from 'vitest';
|
||||
import { me } from '../api/client';
|
||||
import Header from '../components/ui/Header';
|
||||
import { renderWithRouter } from './utils';
|
||||
import { renderWithAuth } from './utils';
|
||||
|
||||
vi.mock('../api/client', () => ({
|
||||
TOKEN_KEY: 'AUTH_TOKEN',
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
me: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('Header', () => {
|
||||
afterEach(() => {
|
||||
localStorage.clear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders the brand with the logo', () => {
|
||||
renderWithRouter(<Header />);
|
||||
renderWithAuth(<Header />);
|
||||
const brand = screen.getByRole('link', { name: 'newzy' });
|
||||
expect(brand).toHaveAttribute('href', '/');
|
||||
expect(brand.querySelector('img')).toHaveAttribute('src', expect.stringContaining('logo'));
|
||||
});
|
||||
|
||||
it('renders the primary navigation with router links and lucide icons', () => {
|
||||
renderWithRouter(<Header />);
|
||||
renderWithAuth(<Header />);
|
||||
|
||||
const nav = screen.getByRole('navigation', { name: 'Main navigation' });
|
||||
expect(within(nav).getByRole('link', { name: /home/i })).toHaveAttribute('href', '/');
|
||||
@@ -24,7 +39,7 @@ describe('Header', () => {
|
||||
});
|
||||
|
||||
it('marks the active route in the navigation', () => {
|
||||
renderWithRouter(<Header />, { route: '/categories' });
|
||||
renderWithAuth(<Header />, { route: '/categories' });
|
||||
|
||||
const nav = screen.getByRole('navigation', { name: 'Main navigation' });
|
||||
expect(within(nav).getByRole('link', { name: /categories/i })).toHaveClass('bg-blue-50');
|
||||
@@ -32,7 +47,7 @@ describe('Header', () => {
|
||||
});
|
||||
|
||||
it('toggles the mobile menu', () => {
|
||||
renderWithRouter(<Header />);
|
||||
renderWithAuth(<Header />);
|
||||
|
||||
// Mobile menu is closed by default.
|
||||
expect(screen.queryByRole('navigation', { name: 'Mobile navigation' })).not.toBeInTheDocument();
|
||||
@@ -50,6 +65,35 @@ describe('Header', () => {
|
||||
screen.queryByRole('navigation', { name: 'Mobile navigation' }),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows sign-in and register links when signed out', async () => {
|
||||
renderWithAuth(<Header />);
|
||||
|
||||
const accountNav = screen.getByRole('navigation', { name: 'Account' });
|
||||
expect(await within(accountNav).findByRole('link', { name: 'Sign in' })).toHaveAttribute(
|
||||
'href',
|
||||
'/login',
|
||||
);
|
||||
expect(within(accountNav).getByRole('link', { name: /register/i })).toHaveAttribute(
|
||||
'href',
|
||||
'/register',
|
||||
);
|
||||
expect(within(accountNav).queryByRole('link', { name: /sign out/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the username and sign-out link when signed in', async () => {
|
||||
(me as Mock).mockResolvedValue({ username: 'alice' });
|
||||
localStorage.setItem('AUTH_TOKEN', 'stored-token');
|
||||
|
||||
renderWithAuth(<Header />);
|
||||
|
||||
const accountNav = screen.getByRole('navigation', { name: 'Account' });
|
||||
expect(await within(accountNav).findByText('alice')).toBeInTheDocument();
|
||||
expect(within(accountNav).getByRole('link', { name: 'Sign out' })).toHaveAttribute(
|
||||
'href',
|
||||
'/sign-out',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const NAV_ITEM_COUNT = 3;
|
||||
@@ -3,10 +3,15 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { Mock } from 'vitest';
|
||||
import { getHealth } from '../api/client';
|
||||
import Layout from '../components/ui/Layout';
|
||||
import { renderWithRouter } from './utils';
|
||||
import { renderWithAuth } from './utils';
|
||||
|
||||
vi.mock('../api/client', () => ({
|
||||
getHealth: vi.fn(),
|
||||
TOKEN_KEY: 'AUTH_TOKEN',
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
me: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('Layout', () => {
|
||||
@@ -17,7 +22,7 @@ describe('Layout', () => {
|
||||
it('renders the header, main content area and footer', () => {
|
||||
(getHealth as Mock).mockRejectedValue(new Error('offline'));
|
||||
|
||||
renderWithRouter(
|
||||
renderWithAuth(
|
||||
<Layout>
|
||||
<p>Page content</p>
|
||||
</Layout>,
|
||||
@@ -33,7 +38,7 @@ describe('Layout', () => {
|
||||
it('shows the API as online when the health check succeeds', async () => {
|
||||
(getHealth as Mock).mockResolvedValue({ status: 'ok', version: '0.1.0' });
|
||||
|
||||
renderWithRouter(
|
||||
renderWithAuth(
|
||||
<Layout>
|
||||
<p>content</p>
|
||||
</Layout>,
|
||||
@@ -46,7 +51,7 @@ describe('Layout', () => {
|
||||
it('shows the API as offline when the health check fails', async () => {
|
||||
(getHealth as Mock).mockRejectedValue(new Error('offline'));
|
||||
|
||||
renderWithRouter(
|
||||
renderWithAuth(
|
||||
<Layout>
|
||||
<p>content</p>
|
||||
</Layout>,
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { Mock } from 'vitest';
|
||||
import {
|
||||
TOKEN_KEY,
|
||||
login as clientLogin,
|
||||
logout as clientLogout,
|
||||
me as clientMe,
|
||||
register as clientRegister,
|
||||
} from '../api/client';
|
||||
import { AuthProvider, RequireAuth, useAuth } from '../auth';
|
||||
import { renderWithAuth } from './utils';
|
||||
|
||||
vi.mock('../api/client', () => ({
|
||||
TOKEN_KEY: 'AUTH_TOKEN',
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
me: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}));
|
||||
|
||||
/** Renders the current auth state plus one trigger button per action. */
|
||||
function StateProbe() {
|
||||
const { username, ready, login, register, logout } = useAuth();
|
||||
return (
|
||||
<div>
|
||||
<span data-testid="ready">{String(ready)}</span>
|
||||
<span data-testid="username">{username ?? 'null'}</span>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="do-login"
|
||||
onClick={() => {
|
||||
void login('login-user', 'password123');
|
||||
}}
|
||||
>
|
||||
login
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="do-register"
|
||||
onClick={() => {
|
||||
void register('register-user', 'password123');
|
||||
}}
|
||||
>
|
||||
register
|
||||
</button>
|
||||
<button type="button" data-testid="do-logout" onClick={logout}>
|
||||
logout
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
describe('AuthProvider', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('starts signed out without a stored token (no me() call)', async () => {
|
||||
renderWithAuth(<StateProbe />);
|
||||
expect(await screen.findByTestId('ready')).toHaveTextContent('true');
|
||||
expect(screen.getByTestId('username')).toHaveTextContent('null');
|
||||
expect(clientMe).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('restores the session from a valid stored token', async () => {
|
||||
(clientMe as Mock).mockResolvedValue({ username: 'alice' });
|
||||
localStorage.setItem(TOKEN_KEY, 'valid-token');
|
||||
|
||||
renderWithAuth(<StateProbe />);
|
||||
|
||||
expect(await screen.findByTestId('username')).toHaveTextContent('alice');
|
||||
expect(clientMe).toHaveBeenCalledWith('valid-token');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBe('valid-token');
|
||||
});
|
||||
|
||||
it('clears an invalid stored token on restore failure', async () => {
|
||||
(clientMe as Mock).mockRejectedValue(new Error('401'));
|
||||
localStorage.setItem(TOKEN_KEY, 'expired-token');
|
||||
|
||||
renderWithAuth(<StateProbe />);
|
||||
|
||||
expect(await screen.findByTestId('ready')).toHaveTextContent('true');
|
||||
expect(screen.getByTestId('username')).toHaveTextContent('null');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
|
||||
});
|
||||
|
||||
it('login stores the returned token and sets the username', async () => {
|
||||
(clientLogin as Mock).mockResolvedValue({ token: 'new-token', username: 'login-user' });
|
||||
|
||||
renderWithAuth(<StateProbe />);
|
||||
await screen.findByTestId('ready');
|
||||
screen.getByTestId('do-login').click();
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('username')).toHaveTextContent('login-user'));
|
||||
expect(clientLogin).toHaveBeenCalledWith('login-user', 'password123');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBe('new-token');
|
||||
});
|
||||
|
||||
it('register stores the returned token and sets the username', async () => {
|
||||
(clientRegister as Mock).mockResolvedValue({
|
||||
token: 'new-token',
|
||||
username: 'register-user',
|
||||
});
|
||||
|
||||
renderWithAuth(<StateProbe />);
|
||||
await screen.findByTestId('ready');
|
||||
screen.getByTestId('do-register').click();
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('username')).toHaveTextContent('register-user'),
|
||||
);
|
||||
expect(clientRegister).toHaveBeenCalledWith('register-user', 'password123');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBe('new-token');
|
||||
});
|
||||
|
||||
it('logout calls the API best-effort and clears the session', async () => {
|
||||
(clientMe as Mock).mockResolvedValue({ username: 'alice' });
|
||||
(clientLogout as Mock).mockResolvedValue(undefined);
|
||||
localStorage.setItem(TOKEN_KEY, 'valid-token');
|
||||
|
||||
renderWithAuth(<StateProbe />);
|
||||
await waitFor(() => expect(screen.getByTestId('username')).toHaveTextContent('alice'));
|
||||
screen.getByTestId('do-logout').click();
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('username')).toHaveTextContent('null'));
|
||||
expect(clientLogout).toHaveBeenCalledTimes(1);
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
|
||||
});
|
||||
|
||||
it('logout still clears the session when the API call fails', async () => {
|
||||
(clientMe as Mock).mockResolvedValue({ username: 'alice' });
|
||||
(clientLogout as Mock).mockRejectedValue(new Error('network down'));
|
||||
localStorage.setItem(TOKEN_KEY, 'valid-token');
|
||||
|
||||
renderWithAuth(<StateProbe />);
|
||||
await waitFor(() => expect(screen.getByTestId('username')).toHaveTextContent('alice'));
|
||||
screen.getByTestId('do-logout').click();
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('username')).toHaveTextContent('null'));
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('RequireAuth', () => {
|
||||
const routes = (
|
||||
<Routes>
|
||||
<Route path="/login" element={<div>Login page</div>} />
|
||||
<Route
|
||||
path="/account"
|
||||
element={
|
||||
<RequireAuth>
|
||||
<div>Account page</div>
|
||||
</RequireAuth>
|
||||
}
|
||||
/>
|
||||
</Routes>
|
||||
);
|
||||
|
||||
const renderProtected = (initialPath: string) =>
|
||||
render(
|
||||
<MemoryRouter
|
||||
initialEntries={[initialPath]}
|
||||
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
|
||||
>
|
||||
<AuthProvider>{routes}</AuthProvider>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('redirects unauthenticated users to /login', async () => {
|
||||
renderProtected('/account');
|
||||
expect(await screen.findByText('Login page')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders protected content for a signed-in user', async () => {
|
||||
(clientMe as Mock).mockResolvedValue({ username: 'alice' });
|
||||
localStorage.setItem(TOKEN_KEY, 'valid-token');
|
||||
|
||||
renderProtected('/account');
|
||||
expect(await screen.findByText('Account page')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* Unit tests for the auth methods of the API client (token attachment,
|
||||
* 401 handling, request/response shapes).
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { ApiError, login, logout, me, register, TOKEN_KEY } from '../api/client';
|
||||
|
||||
/** Minimal fetch Response look-alike for the client. */
|
||||
function jsonResponse(status: number, body: unknown) {
|
||||
return {
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
statusText: 'OK',
|
||||
json: async () => body,
|
||||
text: async () => JSON.stringify(body),
|
||||
} as Response;
|
||||
}
|
||||
|
||||
describe('auth API client', () => {
|
||||
let fetchMock: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
fetchMock = vi.fn();
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
});
|
||||
|
||||
it('login posts credentials to /auth/login and returns the token payload', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, { token: 'tok', username: 'alice' }));
|
||||
|
||||
const res = await login('alice', 'password123');
|
||||
|
||||
expect(res).toEqual({ token: 'tok', username: 'alice' });
|
||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('/api/v1/auth/login');
|
||||
expect(init.method).toBe('POST');
|
||||
expect(JSON.parse(init.body as string)).toEqual({
|
||||
username: 'alice',
|
||||
password: 'password123',
|
||||
});
|
||||
});
|
||||
|
||||
it('register posts to /auth/register', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(201, { token: 'tok', username: 'bob' }));
|
||||
|
||||
await register('bob', 'password123');
|
||||
|
||||
const [url] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('/api/v1/auth/register');
|
||||
});
|
||||
|
||||
it('attaches the stored token as a Bearer Authorization header', async () => {
|
||||
localStorage.setItem(TOKEN_KEY, 'stored-token');
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, { username: 'alice' }));
|
||||
|
||||
await me();
|
||||
|
||||
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect((init.headers as Record<string, string>).Authorization).toBe(
|
||||
'Bearer stored-token',
|
||||
);
|
||||
});
|
||||
|
||||
it('sends no Authorization header without a stored token', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, { username: 'alice' }));
|
||||
|
||||
await me();
|
||||
|
||||
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect((init.headers as Record<string, string>).Authorization).toBeUndefined();
|
||||
});
|
||||
|
||||
it('me() prefers an explicit token over the stored one', async () => {
|
||||
localStorage.setItem(TOKEN_KEY, 'stored-token');
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, { username: 'alice' }));
|
||||
|
||||
await me('explicit-token');
|
||||
|
||||
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect((init.headers as Record<string, string>).Authorization).toBe(
|
||||
'Bearer explicit-token',
|
||||
);
|
||||
});
|
||||
|
||||
it('drops the stored token on a 401 response', async () => {
|
||||
localStorage.setItem(TOKEN_KEY, 'dead-token');
|
||||
fetchMock.mockResolvedValue(
|
||||
jsonResponse(401, { detail: 'Invalid or expired token', code: 'unauthorized' }),
|
||||
);
|
||||
|
||||
await expect(me('dead-token')).rejects.toBeInstanceOf(ApiError);
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
|
||||
});
|
||||
|
||||
it('surfaces the backend error detail for failed registrations', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
jsonResponse(400, { detail: 'Username already exists', code: 'bad_request' }),
|
||||
);
|
||||
|
||||
const err = await register('alice', 'password123').catch((e: unknown) => e);
|
||||
|
||||
expect(err).toBeInstanceOf(ApiError);
|
||||
expect((err as ApiError).status).toBe(400);
|
||||
expect((err as ApiError).code).toBe('bad_request');
|
||||
expect((err as ApiError).message).toBe('Username already exists');
|
||||
});
|
||||
|
||||
it('logout posts to /auth/logout and resolves to undefined', async () => {
|
||||
fetchMock.mockResolvedValue({
|
||||
ok: true,
|
||||
status: 204,
|
||||
statusText: 'No Content',
|
||||
} as Response);
|
||||
|
||||
await expect(logout()).resolves.toBeUndefined();
|
||||
|
||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('/api/v1/auth/logout');
|
||||
expect(init.method).toBe('POST');
|
||||
expect(init.body).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { Mock } from 'vitest';
|
||||
import { TOKEN_KEY, login as clientLogin } from '../../api/client';
|
||||
import { AuthProvider } from '../../auth';
|
||||
import Login from '../../pages/Login';
|
||||
|
||||
vi.mock('../../api/client', () => ({
|
||||
TOKEN_KEY: 'AUTH_TOKEN',
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
me: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}));
|
||||
|
||||
function renderLogin() {
|
||||
return (
|
||||
<MemoryRouter
|
||||
initialEntries={['/login']}
|
||||
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
|
||||
>
|
||||
<AuthProvider>
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/" element={<div>Home page</div>} />
|
||||
</Routes>
|
||||
</AuthProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
}
|
||||
|
||||
async function fillLoginForm(username: string, password: string) {
|
||||
fireEvent.change(screen.getByLabelText('Username'), { target: { value: username } });
|
||||
fireEvent.change(screen.getByLabelText('Password'), { target: { value: password } });
|
||||
const form = screen.getByRole('button', { name: /sign in/i }).closest('form');
|
||||
expect(form).not.toBeNull();
|
||||
fireEvent.submit(form as HTMLFormElement);
|
||||
}
|
||||
|
||||
describe('Login page', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders the form fields and a link to registration', () => {
|
||||
render(renderLogin());
|
||||
expect(screen.getByLabelText('Username')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Password')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /sign in/i })).toBeEnabled();
|
||||
expect(screen.getByRole('link', { name: /register/i })).toHaveAttribute('href', '/register');
|
||||
});
|
||||
|
||||
it('blocks submission with empty fields', async () => {
|
||||
render(renderLogin());
|
||||
await screen.findByTestId('login-card');
|
||||
|
||||
const form = screen.getByRole('button', { name: /sign in/i }).closest('form');
|
||||
fireEvent.submit(form as HTMLFormElement);
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(
|
||||
'Please enter both username and password.',
|
||||
);
|
||||
expect(clientLogin).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('signs in, stores the token and navigates to home', async () => {
|
||||
(clientLogin as Mock).mockResolvedValue({ token: 'tok-123', username: 'alice' });
|
||||
render(renderLogin());
|
||||
await screen.findByTestId('login-card');
|
||||
|
||||
await fillLoginForm('alice', 'password123');
|
||||
|
||||
expect(await screen.findByText('Home page')).toBeInTheDocument();
|
||||
expect(clientLogin).toHaveBeenCalledWith('alice', 'password123');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBe('tok-123');
|
||||
});
|
||||
|
||||
it('shows the backend error on failed login and stores no token', async () => {
|
||||
(clientLogin as Mock).mockRejectedValue(
|
||||
new Error('Invalid username or password'),
|
||||
);
|
||||
render(renderLogin());
|
||||
await screen.findByTestId('login-card');
|
||||
|
||||
await fillLoginForm('alice', 'wrong-password');
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Invalid username or password');
|
||||
expect(screen.getByRole('button', { name: /sign in/i })).toBeEnabled();
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
|
||||
});
|
||||
|
||||
it('shows a loading state while the login request is pending', async () => {
|
||||
(clientLogin as Mock).mockReturnValue(new Promise(() => undefined));
|
||||
render(renderLogin());
|
||||
await screen.findByTestId('login-card');
|
||||
|
||||
await fillLoginForm('alice', 'password123');
|
||||
|
||||
expect(await screen.findByText('Signing in…')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /signing in/i })).toBeDisabled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { Mock } from 'vitest';
|
||||
import { TOKEN_KEY, register as clientRegister } from '../../api/client';
|
||||
import { AuthProvider } from '../../auth';
|
||||
import Register from '../../pages/Register';
|
||||
|
||||
vi.mock('../../api/client', () => ({
|
||||
TOKEN_KEY: 'AUTH_TOKEN',
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
me: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}));
|
||||
|
||||
function renderRegister() {
|
||||
return (
|
||||
<MemoryRouter
|
||||
initialEntries={['/register']}
|
||||
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
|
||||
>
|
||||
<AuthProvider>
|
||||
<Routes>
|
||||
<Route path="/register" element={<Register />} />
|
||||
<Route path="/" element={<div>Home page</div>} />
|
||||
</Routes>
|
||||
</AuthProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
}
|
||||
|
||||
async function fillRegisterForm(
|
||||
username: string,
|
||||
password: string,
|
||||
confirm: string,
|
||||
): Promise<void> {
|
||||
fireEvent.change(screen.getByLabelText('Username'), { target: { value: username } });
|
||||
fireEvent.change(screen.getByLabelText('Password'), { target: { value: password } });
|
||||
fireEvent.change(screen.getByLabelText('Confirm password'), {
|
||||
target: { value: confirm },
|
||||
});
|
||||
const form = screen.getByRole('button', { name: /register/i }).closest('form');
|
||||
expect(form).not.toBeNull();
|
||||
fireEvent.submit(form as HTMLFormElement);
|
||||
}
|
||||
|
||||
describe('Register page', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders the form fields and a link to login', () => {
|
||||
render(renderRegister());
|
||||
expect(screen.getByLabelText('Username')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Password')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Confirm password')).toBeInTheDocument();
|
||||
expect(screen.getByRole('link', { name: /sign in/i })).toHaveAttribute('href', '/login');
|
||||
});
|
||||
|
||||
it('rejects mismatched passwords without calling the API', async () => {
|
||||
render(renderRegister());
|
||||
await screen.findByTestId('register-card');
|
||||
|
||||
await fillRegisterForm('newuser', 'password123', 'different123');
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Passwords do not match.');
|
||||
expect(clientRegister).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects invalid usernames without calling the API', async () => {
|
||||
render(renderRegister());
|
||||
await screen.findByTestId('register-card');
|
||||
|
||||
await fillRegisterForm('ab', 'password123', 'password123');
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(/3–20 characters/);
|
||||
expect(clientRegister).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects short passwords without calling the API', async () => {
|
||||
render(renderRegister());
|
||||
await screen.findByTestId('register-card');
|
||||
|
||||
await fillRegisterForm('newuser', 'short', 'short');
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(/at least 8 characters/);
|
||||
expect(clientRegister).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('registers, stores the token and navigates to home', async () => {
|
||||
(clientRegister as Mock).mockResolvedValue({ token: 'tok-456', username: 'newuser' });
|
||||
render(renderRegister());
|
||||
await screen.findByTestId('register-card');
|
||||
|
||||
await fillRegisterForm('newuser', 'password123', 'password123');
|
||||
|
||||
expect(await screen.findByText('Home page')).toBeInTheDocument();
|
||||
expect(clientRegister).toHaveBeenCalledWith('newuser', 'password123');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBe('tok-456');
|
||||
});
|
||||
|
||||
it('shows the backend error for an existing username', async () => {
|
||||
(clientRegister as Mock).mockRejectedValue(
|
||||
new Error('Username already exists'),
|
||||
);
|
||||
render(renderRegister());
|
||||
await screen.findByTestId('register-card');
|
||||
|
||||
await fillRegisterForm('newuser', 'password123', 'password123');
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Username already exists');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,12 +1,52 @@
|
||||
/**
|
||||
* Vitest setup: registers jest-dom matchers and cleans up the DOM after
|
||||
* every test (React Testing Library auto-cleanup needs this when globals
|
||||
* are disabled).
|
||||
* Vitest setup: registers jest-dom matchers, provides a working
|
||||
* `localStorage` and cleans up the DOM after every test (React Testing
|
||||
* Library auto-cleanup needs this when globals are disabled).
|
||||
*/
|
||||
import '@testing-library/jest-dom/vitest';
|
||||
import { cleanup } from '@testing-library/react';
|
||||
import { afterEach } from 'vitest';
|
||||
|
||||
/**
|
||||
* In-memory Storage. Node >= 22 exposes an experimental `localStorage`
|
||||
* global that is `undefined` without `--localstorage-file`, and the jsdom
|
||||
* environment does not override it — so the auth tests (which persist the
|
||||
* JWT under AUTH_TOKEN) get a real storage implementation here.
|
||||
*/
|
||||
class MemoryStorage implements Storage {
|
||||
private store = new Map<string, string>();
|
||||
|
||||
get length(): number {
|
||||
return this.store.size;
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.store.clear();
|
||||
}
|
||||
|
||||
getItem(key: string): string | null {
|
||||
return this.store.has(key) ? this.store.get(key)! : null;
|
||||
}
|
||||
|
||||
key(index: number): string | null {
|
||||
return Array.from(this.store.keys())[index] ?? null;
|
||||
}
|
||||
|
||||
removeItem(key: string): void {
|
||||
this.store.delete(key);
|
||||
}
|
||||
|
||||
setItem(key: string, value: string): void {
|
||||
this.store.set(key, String(value));
|
||||
}
|
||||
}
|
||||
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: new MemoryStorage(),
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
@@ -1,12 +1,23 @@
|
||||
import { render, type RenderOptions } from '@testing-library/react';
|
||||
import type { ReactElement } from 'react';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { AuthProvider } from '../auth';
|
||||
|
||||
export interface RenderWithRouterOptions extends Omit<RenderOptions, 'wrapper'> {
|
||||
/** Initial route (path only, e.g. "/articles/1"). */
|
||||
route?: string;
|
||||
}
|
||||
|
||||
interface RouterFutureFlags {
|
||||
v7_startTransition: boolean;
|
||||
v7_relativeSplatPath: boolean;
|
||||
}
|
||||
|
||||
const ROUTER_FUTURE: RouterFutureFlags = {
|
||||
v7_startTransition: true,
|
||||
v7_relativeSplatPath: true,
|
||||
};
|
||||
|
||||
/**
|
||||
* Render helper that wraps the UI in a MemoryRouter so components using
|
||||
* react-router-dom (Link, NavLink, useParams) can be tested in isolation.
|
||||
@@ -15,12 +26,26 @@ export function renderWithRouter(ui: ReactElement, options: RenderWithRouterOpti
|
||||
const { route = '/', ...renderOptions } = options;
|
||||
|
||||
return render(
|
||||
<MemoryRouter
|
||||
initialEntries={[route]}
|
||||
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
|
||||
>
|
||||
<MemoryRouter initialEntries={[route]} future={ROUTER_FUTURE}>
|
||||
{ui}
|
||||
</MemoryRouter>,
|
||||
renderOptions,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render helper for auth-aware components: additionally wraps the UI in
|
||||
* the app's `AuthProvider`. Tests that care about the auth API should
|
||||
* mock `../api/client`; with an empty localStorage no network calls are
|
||||
* made during session restore.
|
||||
*/
|
||||
export function renderWithAuth(ui: ReactElement, options: RenderWithRouterOptions = {}) {
|
||||
const { route = '/', ...renderOptions } = options;
|
||||
|
||||
return render(
|
||||
<MemoryRouter initialEntries={[route]} future={ROUTER_FUTURE}>
|
||||
<AuthProvider>{ui}</AuthProvider>
|
||||
</MemoryRouter>,
|
||||
renderOptions,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Auth API types (mirror the backend `schemas.auth` payloads).
|
||||
*/
|
||||
|
||||
/** Payload of `POST /api/v1/auth/register` and `POST /api/v1/auth/login`. */
|
||||
export interface TokenResponse {
|
||||
/** Signed JWT (7-day expiry) — store and send back as `Bearer` token. */
|
||||
token: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
/** Payload of `GET /api/v1/auth/me`. */
|
||||
export interface MeResponse {
|
||||
username: string;
|
||||
}
|
||||
@@ -0,0 +1,489 @@
|
||||
# M5: Setup Authentication
|
||||
|
||||
## Prompt
|
||||
|
||||
Implement complete authentication for **newzy** news web application. Follow the reference implementation pattern from `/home/daniel/Gitea/daniel/news`.
|
||||
|
||||
### Backend Requirements (FastAPI)
|
||||
|
||||
1. Create `backend/app/auth.py` with:
|
||||
- Password hashing using PBKDF2 with salt
|
||||
- JWT token creation and verification
|
||||
- Current user dependency that validates Bearer tokens
|
||||
- Environment variable `HN_SECRET_KEY` for JWT signing (default dev key)
|
||||
|
||||
2. Update `backend/app/models.py` to add User model:
|
||||
- `id`: Integer primary key
|
||||
- `username`: String(60), unique, index
|
||||
- `password_hash`: String(128)
|
||||
- `created_at`: DateTime with default
|
||||
|
||||
3. Create/update authentication endpoints in `backend/app/main.py`:
|
||||
- `POST /api/auth/register` - Register new user, return JWT token
|
||||
- `POST /api/auth/login` - Login, return JWT token
|
||||
- `POST /api/auth/logout` - Logout (clear token, optional)
|
||||
- `GET /api/auth/me` - Return current user info
|
||||
- Password hashing with PBKDF2 (120,000 iterations minimum)
|
||||
|
||||
4. Create/update `backend/requirements.txt`:
|
||||
- Add `python-jose[cryptography]` for JWT
|
||||
- Add `passlib[bcrypt]` or hashlib for password hashing
|
||||
- Ensure all auth dependencies are listed
|
||||
|
||||
5. Update `backend/app/database.py` if needed:
|
||||
- Configure SQLite database properly for user persistence
|
||||
- Ensure models can be created/queried
|
||||
|
||||
6. Create `data/.gitignore` with patterns to exclude:
|
||||
```python
|
||||
*.db
|
||||
*.sqlite
|
||||
data.db
|
||||
newzy.db
|
||||
```
|
||||
|
||||
7. Update project root `docker-compose.yml` if needed:
|
||||
- Add environment variable override for `HN_SECRET_KEY` (optional, default in code)
|
||||
- Ensure database volume is properly mounted
|
||||
|
||||
### Frontend Requirements (React + TypeScript)
|
||||
|
||||
1. Create `frontend/src/types/auth.ts`:
|
||||
```typescript
|
||||
export interface TokenResponse {
|
||||
token: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
export interface MeResponse {
|
||||
username: string;
|
||||
}
|
||||
```
|
||||
|
||||
2. Update `frontend/src/api/client.ts`:
|
||||
- Add methods for auth endpoints: `login(username, password)`, `register(username, password)`, `logout()`, `me()`
|
||||
- Implement JWT token attachment to requests (Authorization: Bearer <token>)
|
||||
- Handle token storage in localStorage
|
||||
|
||||
3. Create `frontend/src/auth.tsx`:
|
||||
- Create AuthContext with username and ready state
|
||||
- Provide login, register, logout functions
|
||||
- On app load, check localStorage for token and call `/api/auth/me` to restore session
|
||||
- If token invalid/expired, clear storage
|
||||
- Export `AuthProvider` component
|
||||
|
||||
4. Create page components:
|
||||
- `frontend/src/pages/Login.tsx`: Login form with username/password validation
|
||||
- `frontend/src/pages/Register.tsx`: Registration form with username/password validation
|
||||
- `frontend/src/pages/SignOut.tsx`: Sign out button that clears token and redirects to login
|
||||
|
||||
5. Update `frontend/src/App.tsx`:
|
||||
- Wrap app with `<AuthProvider>`
|
||||
- Set up protected routes for logged-in users (optional placeholder)
|
||||
|
||||
6. Create CSS styling:
|
||||
- `frontend/src/assets/styles/auth.css` or include in existing styles
|
||||
- Auth pages should be clean, accessible forms
|
||||
- Proper loading states during API calls
|
||||
|
||||
### Shared Requirements
|
||||
|
||||
1. Token Management:
|
||||
- JWT token stored in `localStorage` with key `AUTH_TOKEN`
|
||||
- Tokens have 7-day expiry (7 * 24 * 60 * 60 seconds)
|
||||
- Token format: `sub=USERNAME, iat=TIMESTAMP, exp=TIMESTAMP+7days`
|
||||
|
||||
2. Security:
|
||||
- Passwords hashed with PBKDF2-HMAC-SHA256 (120,000 iterations minimum)
|
||||
- Salt generated using `secrets.token_hex(16)` for uniqueness
|
||||
- JWT signed with HS256 algorithm
|
||||
- Bearer token in Authorization header: `Authorization: Bearer <token>`
|
||||
|
||||
3. Error Handling:
|
||||
- 401 on invalid/expired token
|
||||
- Clear error messages for user actions
|
||||
- Best effort logout on client side
|
||||
|
||||
### Testing Requirements (M3 already covers this)
|
||||
- Unit tests for auth functions
|
||||
- E2E tests for login/register/logout flows
|
||||
|
||||
Remember: Focus ONLY on authentication setup. No complex UI features or business logic required beyond auth endpoints and pages. Use the reference implementation in `/home/daniel/Gitea/daniel/news` as a guide for patterns and structure.
|
||||
|
||||
## Description
|
||||
|
||||
This milestone implements complete JWT-based authentication for newzy news application using FastAPI backend with PBKDF2 password hashing and React frontend with localStorage token management. The scope includes user registration, login, logout, and session restoration—no complex UI features beyond authentication pages.
|
||||
|
||||
**Purpose**: Enable secure user accounts with JWT tokens for protecting content creation and interaction operations in subsequent milestones.
|
||||
|
||||
**Target Audience**: Developers who need to understand the auth flow and extend it with features like profile management or social login.
|
||||
|
||||
**Expected Outcomes**: A fully functional authentication system where users can register, log in, receive JWT tokens, and maintain session state across page reloads. Backend validates tokens against user records. Frontend manages token storage and applies to API requests automatically.
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] User model created with username, password_hash, created_at fields
|
||||
- [ ] Password hashing implemented with PBKDF2 (120,000+ iterations)
|
||||
- [ ] JWT token generation using HS256 algorithm with 7-day expiry
|
||||
- [ ] POST /api/auth/register accepts username/password, returns token
|
||||
- [ ] POST /api/auth/login accepts credentials, returns token
|
||||
- [ ] POST /api/auth/logout clears state (client-side best effort)
|
||||
- [ ] GET /api/auth/me validates Bearer token, returns current user
|
||||
- [ ] Frontend auth.tsx with AuthContext for state management
|
||||
- [ ] Auth pages: Login.tsx, Register.tsx, SignOut.tsx created
|
||||
- [ ] API client includes auth methods with token attachment
|
||||
- [ ] localStorage persistence for AUTH_TOKEN key
|
||||
- [ ] Session restoration on page load (check token validity)
|
||||
- [ ] Token stored in localStorage expires automatically after 7 days
|
||||
- [ ] 401 responses for invalid/missing/expired tokens
|
||||
- [ ] .gitignore excludes database files and sensitive configs
|
||||
|
||||
## Technical Details
|
||||
|
||||
### Backend User Model
|
||||
|
||||
```python
|
||||
# backend/app/models.py
|
||||
|
||||
from datetime import datetime
|
||||
from sqlalchemy import DateTime, ForeignKey, Integer, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
class User(Base):
|
||||
__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)
|
||||
```
|
||||
|
||||
### Password Hashing (PBKDF2)
|
||||
|
||||
```python
|
||||
# backend/app/auth.py
|
||||
|
||||
import hashlib
|
||||
import secrets
|
||||
from typing import Optional
|
||||
|
||||
PBKDF2_ITERATIONS = 120_000
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
"""Generate password hash with random salt."""
|
||||
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 stored hash."""
|
||||
try:
|
||||
salt, digest = stored.split("$", 1)
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
candidate = hashlib.pbkdf2_hmac(
|
||||
"sha256", password.encode(), bytes.fromhex(salt), PBKDF2_ITERATIONS
|
||||
).hex()
|
||||
|
||||
return secrets.compare_digest(candidate, digest)
|
||||
```
|
||||
|
||||
### JWT Token Creation & Verification
|
||||
|
||||
```python
|
||||
# backend/app/auth.py
|
||||
|
||||
import jwt
|
||||
import os
|
||||
from fastapi import Depends, HTTPException
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
|
||||
SECRET_KEY = os.environ.get("HN_SECRET_KEY", "hn-clone-dev-secret-change-me")
|
||||
ALGORITHM = "HS256"
|
||||
TOKEN_TTL_SECONDS = 7 * 24 * 60 * 60 # 7 days
|
||||
|
||||
_bearer = HTTPBearer(auto_error=False)
|
||||
|
||||
def create_token(username: str) -> str:
|
||||
"""Create JWT token for user."""
|
||||
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: Optional[HTTPAuthorizationCredentials] = Depends(_bearer),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
"""Validate Bearer token and return user data."""
|
||||
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 e:
|
||||
raise HTTPException(status_code=401, detail="Invalid or expired token")
|
||||
|
||||
username = payload.get("sub")
|
||||
user = db.query(User).filter(User.username == username).first()
|
||||
|
||||
if not user:
|
||||
raise HTTPException(status_code=401, detail="Unknown user")
|
||||
|
||||
return user
|
||||
```
|
||||
|
||||
### Authentication Endpoints (FastAPI)
|
||||
|
||||
```python
|
||||
# backend/app/main.py
|
||||
|
||||
@app.post("/api/auth/register", response_model=dict)
|
||||
async def register(username: str, password: str):
|
||||
"""Register new user."""
|
||||
# Validate username (alphanumeric, 3-20 chars)
|
||||
if not re.match(r'^[a-zA-Z0-9_]{3,20}$', username):
|
||||
raise HTTPException(status_code=400, detail="Invalid username")
|
||||
|
||||
# Check user doesn't exist
|
||||
existing = db.query(User).filter(User.username == username).first()
|
||||
if existing:
|
||||
raise HTTPException(status_code=400, detail="Username already exists")
|
||||
|
||||
# Create user with hashed password
|
||||
new_user = User(
|
||||
username=username,
|
||||
password_hash=hash_password(password)
|
||||
)
|
||||
db.add(new_user)
|
||||
db.commit()
|
||||
|
||||
# Return JWT token
|
||||
return {
|
||||
"token": create_token(username),
|
||||
"username": username
|
||||
}
|
||||
|
||||
@app.post("/api/auth/login", response_model=dict)
|
||||
async def login(username: str, password: str):
|
||||
"""Authenticate and return JWT token."""
|
||||
user = db.query(User).filter(User.username == username).first()
|
||||
if not user or not verify_password(password, user.password_hash):
|
||||
raise HTTPException(status_code=401, detail="Invalid credentials")
|
||||
|
||||
return {
|
||||
"token": create_token(username),
|
||||
"username": username
|
||||
}
|
||||
|
||||
@app.get("/api/auth/me", response_model=dict)
|
||||
async def get_current_user_info(user: dict = Depends(get_current_user)):
|
||||
"""Return current user data."""
|
||||
return {"username": user.username}
|
||||
|
||||
@app.post("/api/auth/logout", status_code=204)
|
||||
async def logout():
|
||||
"""Logout (stateless - token discarded on client side)."""
|
||||
pass # Optional: server-side invalidation if needed
|
||||
```
|
||||
|
||||
### Frontend Auth Context
|
||||
|
||||
```typescript
|
||||
// frontend/src/auth.tsx
|
||||
|
||||
interface TokenResponse {
|
||||
token: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
const TOKEN_KEY = "AUTH_TOKEN";
|
||||
|
||||
export interface AuthState {
|
||||
username: string | null;
|
||||
ready: boolean;
|
||||
login: (username: string, password: string) => Promise<void>;
|
||||
register: (username: string, password: string) => Promise<void>;
|
||||
logout: () => void;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthState | null>(null);
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [username, setUsername] = useState<string | null>(null);
|
||||
const [ready, setReady] = useState(false);
|
||||
|
||||
// Restore session on load
|
||||
useEffect(() => {
|
||||
const stored = localStorage.getItem(TOKEN_KEY);
|
||||
if (!stored) {
|
||||
setReady(true);
|
||||
return;
|
||||
}
|
||||
|
||||
api.me(stored)
|
||||
.then((user) => setUsername(user.username))
|
||||
.catch(() => localStorage.removeItem(TOKEN_KEY))
|
||||
.finally(() => setReady(true));
|
||||
}, []);
|
||||
|
||||
const login = useCallback(async (username: string, password: string) => {
|
||||
const res = await api.login(username, password);
|
||||
localStorage.setItem(TOKEN_KEY, res.token);
|
||||
setUsername(res.username);
|
||||
}, [api]);
|
||||
|
||||
const register = useCallback(async (username: string, password: string) => {
|
||||
const res = await api.register(username, password);
|
||||
localStorage.setItem(TOKEN_KEY, res.token);
|
||||
setUsername(res.username);
|
||||
}, [api]);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
// Best effort logout
|
||||
api.logout().catch(() => {});
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
setUsername(null);
|
||||
}, [api]);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ username, ready, login, register, logout }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### API Client with Auth Methods
|
||||
|
||||
```typescript
|
||||
// frontend/src/api/client.ts
|
||||
|
||||
export const api = {
|
||||
async login(username: string, password: string): Promise<TokenResponse> {
|
||||
const res = await fetch('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password })
|
||||
});
|
||||
|
||||
if (!res.ok) throw new Error('Login failed');
|
||||
return res.json();
|
||||
},
|
||||
|
||||
async register(username: string, password: string): Promise<TokenResponse> {
|
||||
const res = await fetch('/api/auth/register', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password })
|
||||
});
|
||||
|
||||
if (!res.ok) throw new Error('Registration failed');
|
||||
return res.json();
|
||||
},
|
||||
|
||||
async me(token: string): Promise<{ username: string }> {
|
||||
const res = await fetch('/api/auth/me', {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
|
||||
if (!res.ok) throw new Error('Invalid token');
|
||||
return res.json();
|
||||
},
|
||||
|
||||
async logout(): Promise<void> {
|
||||
try {
|
||||
await fetch('/api/auth/logout', { method: 'POST' });
|
||||
} catch (e) {
|
||||
// Best effort - discard token anyway
|
||||
}
|
||||
},
|
||||
|
||||
// Other API methods with token attachment...
|
||||
};
|
||||
```
|
||||
|
||||
### Login/Register Pages Structure
|
||||
|
||||
**Login.tsx:**
|
||||
- Form with username and password fields
|
||||
- Submit button with loading state
|
||||
- Validation for empty/invalid inputs
|
||||
- Redirect to dashboard after successful login
|
||||
|
||||
**Register.tsx:**
|
||||
- Form with username, password, confirm password fields
|
||||
- Validation: unique username, matching passwords, minimum lengths
|
||||
- Error messages for existing usernames or weak passwords
|
||||
- Redirect to login after successful registration
|
||||
|
||||
### Security Configuration
|
||||
|
||||
```python
|
||||
# .env.example (project root)
|
||||
|
||||
HN_SECRET_KEY=your-secret-key-change-in-production
|
||||
```
|
||||
|
||||
**Important**: Change `HN_SECRET_KEY` in production! Default dev key should never be used.
|
||||
|
||||
## QA Notes
|
||||
|
||||
### Testing Checklist - Backend
|
||||
- [ ] User registration creates account with hashed password
|
||||
- [ ] Duplicate username rejection with 400 status
|
||||
- [ ] Login validates credentials and returns token
|
||||
- [ ] Invalid credentials return 401
|
||||
- [ ] JWT token has correct expiry (7 days)
|
||||
- [ ] Token verification checks against database
|
||||
- [ ] Unknown user on /api/auth/me returns 401
|
||||
- [ ] Missing/expired Bearer token returns 401
|
||||
|
||||
### Testing Checklist - Frontend
|
||||
- [ ] AuthContext provides login, register, logout functions
|
||||
- [ ] localStorage persists AUTH_TOKEN correctly
|
||||
- [ ] Session restores on page load (validates token)
|
||||
- [ ] Invalid token cleared from storage on error
|
||||
- [ ] Login form validates inputs before submission
|
||||
- [ ] Register form checks username uniqueness
|
||||
- [ ] Protected routes redirect unauthenticated users to login
|
||||
- [ ] Logout clears token and navigates to login
|
||||
|
||||
### Security Review Checklist
|
||||
- [x] Passwords never stored as plaintext
|
||||
- [x] JWT signed with strong secret (not hardcoded)
|
||||
- [x] PBKDF2 iterations >= 120,000
|
||||
- [x] Salt generated per-password using secrets module
|
||||
- [x] Username validation prevents injection attacks
|
||||
- [x] Token expiry set to prevent session hijacking
|
||||
- [ ] CSRF protection not needed (stateless auth)
|
||||
|
||||
### Performance Considerations
|
||||
- JWT creation should be fast (<1ms)
|
||||
- Password hashing takes ~100-200ms (PBKDF2) - acceptable for login
|
||||
- Database queries cached where possible
|
||||
- Frontend token storage doesn't impact performance
|
||||
|
||||
### Known Issues / Limitations
|
||||
- PBKDF2 is slower than bcrypt - may need async handling
|
||||
- JWT tokens don't expire until 7 days (no refresh tokens)
|
||||
- No rate limiting on auth endpoints yet
|
||||
- Password reset not implemented
|
||||
- Email verification not implemented
|
||||
- Account locking after failed attempts not implemented
|
||||
|
||||
### Success Metrics
|
||||
- Registration complete in <2 seconds with validation feedback
|
||||
- Login completes in <500ms (excluding network)
|
||||
- JWT token format valid and decodable
|
||||
- Session persists across browser restarts within 7 days
|
||||
- Security headers present (CORS configured appropriately)
|
||||
- No plaintext passwords in database or logs
|
||||
Reference in new issue
Block a user