Files
sales-trainer/backend/app/api/auth_routes.py
T
Macky 3c22d88bcd feat: demo SaaS + training flow security hardening (8/8 review gate passed)
- Demo accounts: super_admin-only provisioning into isolated DEMO_ORG_ID tenant,
  30-day UTC trial on first login, revocable, one-time credential delivery via
  optional SES/webhook (never persisted). Adds boto3 dependency.
- Analytics/report/export/privacy: shared bounded scan budget across users/groups/
  sessions, tenant-consistent session/user/group joins, scalar-only CSV export
  (no nested persisted-value stringification).
- Ownership/tenant isolation: canonical owner-tenant predicate for list/read/chat;
  client sees is_owned only, never owner_user_id.
- Lifecycle/races: status transition validation, analyzing is an in-progress gate
  (no duplicate reanalysis), structured-ready publication, stale-variant revalidation.
- Auth/setup/consent/JWT/OAuth/config: fail-closed consent, bounded JWT lifetime,
  provider-subject atomic OAuth identity, repeated-secret rejection, strict Persona
  trait validation.
- Chat/session/privacy: pre-seller opener redaction, corrupt-session recovery,
  role-aware completed-chat dashboard routing.
- Frontend: Training→product→personas→practice flow, demo/role/demo guards,
  is_owned-based ownership display, 320×568 and 500×768 responsive E2E.
- 8 independent exact-five-key review scopes passed; backend 509, frontend 26,
  production build 1775 modules, isolated E2E 15.
2026-08-25 06:39:06 +07:00

270 lines
10 KiB
Python

"""Auth routes: login, current user, first-time admin setup, self-registration.
Self-registration creates a default-role (``user``) seat-checked account in a
default org. Privileged bootstrap is handled only by the application factory;
public registration can never grant an administrative role.
"""
from __future__ import annotations
from flask import Blueprint, jsonify, request
from ..auth.users import (
AuthError,
SetupAlreadyCompletedError,
is_valid_tenant_id,
utc_now,
)
from ..config import Config
from .helpers import ApiError, current_user, internal_error, request_json_object, require_auth
auth_bp = Blueprint("auth", __name__)
def _store():
from flask import current_app
return current_app.extensions["user_store"]
def _ensure_register_org():
"""Return an active org for self-registration (mirror OAuth default-org).
Prefer ``OAUTH_DEFAULT_ORG`` when configured; otherwise fall back to the
platform default org. The org is created once (locked) if missing so new
signups pass the SaaS tenant gate. Seats are enforced by create_user.
"""
store = _store()
org_id = Config.OAUTH_DEFAULT_ORG or "org-default"
if not is_valid_tenant_id(org_id) or Config._is_placeholder(org_id):
raise ApiError("registration is unavailable", 503)
org = store.get_org_or_none(org_id)
if org is None:
with store.orgs.record_lock(org_id):
org = store.orgs.get_or_none(org_id)
if org is None:
org = store.create_org("Public Signups", org_id=org_id)
if org is None or org.get("active") is not True:
raise ApiError("registration is unavailable", 503)
return org_id
def _login_body(data: dict) -> str:
# Accept `username` (primary) or `email` (fallback), lower-cased.
ident = data.get("username")
if ident is None:
ident = data.get("email")
if not isinstance(ident, str):
return ""
return ident.strip().lower()
@auth_bp.post("/login")
def login():
data = request_json_object()
username = _login_body(data)
password = data.get("password")
if not username or not isinstance(password, str) or not password:
raise ApiError("username and password are required")
# Slow down brute-force / abuse: per-IP + per-username window.
from ..services.rate_limit import check as ratelimit
client_ip = request.remote_addr or "?"
if not ratelimit("login:ip", client_ip, limit=15, window=300):
raise ApiError("too many attempts, try again later", 429)
if not ratelimit("login:user", username, limit=8, window=300):
raise ApiError("too many attempts, try again later", 429)
try:
user = _store().verify(username, password)
if user.get("role") == "demo":
# The trial clock starts only after password verification succeeds.
# start_demo_trial is record-locked so concurrent first logins share
# one exact 30-day UTC window.
user = _store().start_demo_trial(user.get("username") or user.get("id"))
token = _store().issue_token(user)
except AuthError:
raise ApiError("invalid credentials", 401)
public_user = _store().public_user(user)
return jsonify({
"token": token,
"user": public_user,
"must_setup": public_user["must_setup"],
})
@auth_bp.post("/register")
def register():
"""Self-service registration: username + password + email, default role=user.
Seat-checked and lands in the registration default org. The role is always
``user``; deleting all users must never re-arm public super-admin creation.
"""
data = request_json_object(allow_empty=True)
username = data.get("username")
password = data.get("password")
email = data.get("email")
if not isinstance(username, str) or not username.strip():
raise ApiError("username is required", 400)
if not isinstance(password, str) or not password:
raise ApiError("password is required", 400)
if not isinstance(email, str) or not email.strip():
raise ApiError("email is required", 400)
if data.get("accepted_terms") is not True:
raise ApiError("you must accept the Terms of Service and Privacy Policy to continue", 400)
from ..services.rate_limit import check as ratelimit
client_ip = request.remote_addr or "?"
if not ratelimit("register:ip", client_ip, limit=10, window=300):
raise ApiError("too many attempts, try again later", 429)
ident = (username or "").strip().lower()
if not ratelimit("register:user", ident, limit=5, window=300):
raise ApiError("too many attempts, try again later", 429)
store = _store()
org_id = _ensure_register_org()
try:
with store.users.collection_lock():
user = store.create_user(
org_id=org_id,
username=username,
password=password,
name=username,
role="user",
email=email,
must_setup=False,
accepted_terms=True,
_users_lock_held=True,
)
token = store.issue_token(user)
except AuthError as exc:
# Generic; never leak why (seats / uniqueness / inactive org / invalid input).
if str(exc) in (
"organization seat limit reached",
"organization has no available seats",
):
raise ApiError("registration is full", 422)
raise internal_error("registration failed", exc, 400)
except (OSError, TypeError, ValueError, UnicodeError, OverflowError) as exc:
raise internal_error("registration failed", exc, 503)
public_user = store.public_user(user)
return jsonify({
"token": token,
"user": public_user,
"must_setup": public_user["must_setup"],
}), 201
@auth_bp.get("/me")
@require_auth
def me():
return jsonify({"user": _store().public_user(current_user())})
@auth_bp.post("/setup")
@require_auth
def setup():
"""First-time admin setup: set email + change password, then clear must_setup."""
user = current_user()
data = request_json_object()
raw_username = user.get("username") or user.get("id")
if not isinstance(raw_username, str):
raise ApiError("invalid account state", 401)
username = raw_username.strip().lower()
requested_username_raw = data.get("username")
if requested_username_raw is not None and not isinstance(requested_username_raw, str):
raise ApiError("permission denied", 403)
requested_username = (requested_username_raw or "").strip().lower()
if requested_username and requested_username != username:
raise ApiError("permission denied", 403)
if user.get("must_setup") is False and user.get("accepted_terms") is True:
raise ApiError("setup already completed", 409)
email = data.get("email")
new_password = data.get("password")
# SaaS: consent to Terms/Privacy is required before use.
if data.get("accepted_terms") is not True:
raise ApiError("you must accept the Terms of Service and Privacy Policy to continue", 400)
if email is None or email == "" or new_password is None or new_password == "":
raise ApiError("email and new password are required")
try:
updated = _store().complete_setup(
username,
email,
new_password,
accepted_terms=data.get("accepted_terms"),
server_generated_at=utc_now().isoformat(),
)
except SetupAlreadyCompletedError:
raise ApiError("setup already completed", 409)
except AuthError:
raise ApiError("setup could not be completed", 400)
return jsonify({
"ok": True,
"token": _store().issue_token(updated),
"user": _store().public_user(updated),
"must_setup": False,
})
@auth_bp.patch("/profile")
@require_auth
def profile():
"""Self-service profile update: name (and optional email). Any authenticated user."""
user = current_user()
data = request_json_object()
username = user.get("username") or user.get("id")
updates: dict[str, object] = {}
if "name" in data:
updates["name"] = data.get("name")
if "email" in data:
updates["email"] = data.get("email")
try:
updated = _store().update_user_fields(username, **updates)
except AuthError:
raise ApiError("profile update failed", 400)
return jsonify({"user": _store().public_user(updated)})
@auth_bp.post("/password")
@require_auth
def change_password():
"""Change the authenticated user's password after current-password verification."""
data = request_json_object()
if "username" in data:
# The target is always the authenticated subject; never accept a caller-
# supplied username as an alternate mutation target.
raise ApiError("permission denied", 403)
current_password = data.get("current_password")
new_password = data.get("new_password")
if not isinstance(current_password, str) or not isinstance(new_password, str):
raise ApiError("current and new password are required", 400)
from ..services.rate_limit import check as ratelimit
user = current_user()
username = user.get("username") or user.get("id")
client_ip = request.remote_addr or "?"
if not isinstance(username, str) or not username:
raise ApiError("invalid account state", 401)
if not ratelimit("password-change:user", username, limit=5, window=300):
raise ApiError("too many attempts, try again later", 429)
if not ratelimit("password-change:ip", client_ip, limit=20, window=300):
raise ApiError("too many attempts, try again later", 429)
try:
updated = _store().change_password(
username,
current_password,
new_password,
)
except AuthError as exc:
if str(exc) == "current password is invalid":
raise ApiError("current password is incorrect", 401)
raise ApiError("password change failed", 400)
return jsonify({
"ok": True,
"token": _store().issue_token(updated),
"user": _store().public_user(updated),
})