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
@@ -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)
|
||||
Reference in new issue
Block a user