Files
Aurora-Core/app/api/v1/auth.py
T
NixReaperandClaude Sonnet 5 7bee596a0e
CI / lint (push) Canceled after 0s
CI / typecheck (push) Canceled after 0s
CI / unit-tests (push) Canceled after 0s
CI / integration-tests (push) Canceled after 0s
CI / container-build (push) Canceled after 0s
CI / dependency-audit (push) Canceled after 0s
Add user accounts: registration, login, and JWT auth
The first authenticated-user concept in Aurora Core -- everything else in
this codebase is public, read-only catalog data. Foundation for ratings
and a watchlist (not yet built): POST /auth/register, POST /auth/login,
GET /auth/me.

Security specifics worth knowing:
- Passwords hashed with argon2 (via argon2-cffi), never stored plain or
  logged.
- Login returns an identical 401 for a nonexistent email and a wrong
  password on a real one, including matching response timing
  (burn_time_like_a_password_check) -- otherwise either the status code
  or the timing alone lets a client enumerate registered emails.
- AURORA_SECRET_KEY now actually signs JWTs (previously defined but
  unused anywhere) -- .env.example's existing token_urlsafe(48) guidance
  already produces a long enough key, just flagged its new stakes.
- Email matched case-insensitively via explicit normalization in the
  service layer, not relied on from Pydantic's EmailStr (which does not
  lowercase the local part).

12 new integration tests (register/login/me over real HTTP via the
`client` fixture) plus 10 unit tests for the hashing/JWT logic itself,
following the same-day lesson that only unit tests actually execute
locally without Postgres -- the auth core is tested for real here rather
than only through integration tests that might not run before a deploy.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-06 06:15:39 -05:00

69 lines
2.6 KiB
Python

"""Registration and login (section 17, additive). Public, but rate-limited
like every other unauthenticated endpoint -- see app/core/security.py.
"""
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.deps import get_current_user
from app.core.auth import create_access_token
from app.core.database import get_db
from app.core.ids import aurora_id
from app.core.security import enforce_rate_limit
from app.models.user import User
from app.schemas.auth import LoginRequest, RegisterRequest, TokenOut, UserOut
from app.services.user_service import (
EmailAlreadyRegisteredError,
InvalidCredentialsError,
authenticate_user,
register_user,
)
router = APIRouter(prefix="/auth", tags=["auth"], dependencies=[Depends(enforce_rate_limit)])
def _to_user_out(user: User) -> UserOut:
return UserOut(
id=aurora_id("user", str(user.id)),
email=user.email,
display_name=user.display_name,
created_at=user.created_at,
)
@router.post("/register", response_model=TokenOut, status_code=status.HTTP_201_CREATED)
async def register(body: RegisterRequest, session: AsyncSession = Depends(get_db)) -> TokenOut:
try:
user = await register_user(
session, email=body.email, password=body.password, display_name=body.display_name
)
except EmailAlreadyRegisteredError as exc:
raise HTTPException(
status.HTTP_409_CONFLICT,
{"code": "email_already_registered", "message": "An account with this email already exists."},
) from exc
await session.commit()
return TokenOut(access_token=create_access_token(user.id))
@router.post("/login", response_model=TokenOut)
async def login(body: LoginRequest, session: AsyncSession = Depends(get_db)) -> TokenOut:
try:
user = await authenticate_user(session, email=body.email, password=body.password)
except InvalidCredentialsError as exc:
# Deliberately identical whether the email doesn't exist or the
# password is wrong (see authenticate_user) -- distinguishing them
# here would let a client enumerate registered emails.
raise HTTPException(
status.HTTP_401_UNAUTHORIZED,
{"code": "invalid_credentials", "message": "Incorrect email or password."},
) from exc
return TokenOut(access_token=create_access_token(user.id))
@router.get("/me", response_model=UserOut)
async def get_me(user: User = Depends(get_current_user)) -> UserOut:
return _to_user_out(user)