Skip to content

Authentication — Implementation

How It Works

  • db/auth.py provides: bcrypt password check, UserSession creation, UserSession validation/deletion
  • api/auth.py exposes:
  • POST /auth/login — validates credentials, creates UserSession row, sets mp_session httponly cookie (30-day TTL)
  • GET /auth/me — validates session token from cookie
  • POST /auth/logout — deletes UserSession row, clears cookie
  • React AuthGuard in App.tsx calls GET /auth/me on every load; redirects to /login if session missing or expired

Session Lifecycle

  1. Login → create UserSession row + set mp_session cookie
  2. Page load → AuthGuard validates /auth/me → session row checked for expiry
  3. Expired sessions deleted on first access
  4. Logout → delete session row + clear cookie

Gotchas

  • Cookie is httponly; samesite=lax — not accessible from JavaScript; always sent with same-origin requests
  • New accounts: is_active=False until admin approves; login returns 403 with "Account pending approval"
  • Session token: secrets.token_urlsafe(32) — 43-character URL-safe base64 string
  • Cascade delete: deleting a User row deletes all their UserSession rows and PortfolioSnapshot rows

Creating Users (CLI)

Use scripts/create_user.py for initial admin account setup (interactive, not via the API).