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.
98 lines
3.3 KiB
Python
98 lines
3.3 KiB
Python
"""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
|