Files
sales-trainer/backend/app/api/oauth_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

185 lines
6.8 KiB
Python

"""OAuth social login/register via Google + Facebook.
Public signup is permitted ONLY through a verified social identity. The
provider token is validated server-side (never trusting the client), and a new
user is created in ``OAUTH_DEFAULT_ORG`` (role ``user``, seat-checked). The
provider identity is persisted and is the only key accepted for later login;
email-only account linking is deliberately rejected.
"""
from __future__ import annotations
import secrets
from flask import Blueprint, jsonify, request
from ..auth.users import AuthError, is_valid_tenant_id
from ..config import Config
from ..services import oauth as oauth_svc
from .helpers import ApiError, internal_error, request_json_object
oauth_bp = Blueprint("oauth", __name__)
_PROVIDERS = ("google", "facebook")
def _store():
from flask import current_app
return current_app.extensions["user_store"]
def _disabled() -> ApiError:
return ApiError("OAuth is not configured", 404)
@oauth_bp.get("/oauth/config")
def oauth_config():
"""Which providers are enabled + the public client id/app id per provider.
Never leaks secrets — only booleans and the inherently-public client IDs.
"""
google = Config.oauth_provider_enabled("google")
facebook = Config.oauth_provider_enabled("facebook")
return jsonify(
{
"google": google,
"facebook": facebook,
"google_client_id": Config.OAUTH_GOOGLE_CLIENT_ID if google else "",
"facebook_app_id": Config.OAUTH_FACEBOOK_APP_ID if facebook else "",
}
)
def _unique_username(store, base: str) -> str:
"""Derive a collision-free username matching USERNAME_RE (id == username)."""
candidate = base
counter = 0
while store.get_user_or_none(candidate) is not None:
counter += 1
candidate = f"{base}_{counter}"
return candidate
def _ensure_default_org_user(store, provider: str, provider_sub: str, email: str, display_name: str) -> dict:
"""Create a bound social user only in a pre-provisioned active org."""
org_id = Config.OAUTH_DEFAULT_ORG
if Config._is_placeholder(org_id) or not is_valid_tenant_id(org_id):
raise AuthError("oauth disabled")
org = store.get_org_or_none(org_id)
if org is None or org.get("active") is not True:
raise AuthError("oauth disabled")
prefix = "g_" if provider == "google" else "fb_"
base = f"{prefix}{provider_sub}"
username = _unique_username(store, base)
# Social users don't use password login, but the field must be populated
# validly; a strong random value satisfies the policy without being usable.
password = secrets.token_urlsafe(48)
return store.create_user(
org_id=org_id,
username=username,
password=password,
name=(display_name or username),
role="user",
email=email,
# Social signups have no consent field in the provider token exchange.
# Route new accounts through /auth/setup before allowing SaaS access.
must_setup=True,
accepted_terms=False,
oauth_identity=(provider, provider_sub),
_users_lock_held=True,
)
def _bound_user(store, provider: str, provider_sub: str) -> dict | None:
"""Resolve one canonical provider subject and reject malformed bindings."""
match = None
seen: set[tuple[str, str]] = set()
for user in store.users.all():
identities = user.get("oauth_identities", [])
if not isinstance(identities, list):
raise AuthError("invalid oauth identity state")
for identity in identities:
if (
not isinstance(identity, dict)
or identity.get("provider") not in _PROVIDERS
or not isinstance(identity.get("subject"), str)
or not identity["subject"].strip()
or len(identity["subject"]) > 255
):
raise AuthError("invalid oauth identity state")
identity_key = (identity["provider"], identity["subject"])
if identity_key in seen:
raise AuthError("duplicate oauth identity")
seen.add(identity_key)
if identity["provider"] == provider and identity["subject"] == provider_sub:
match = user
return match
@oauth_bp.post("/oauth")
def oauth_exchange():
data = request_json_object()
provider = data.get("provider")
token = data.get("token")
if provider not in _PROVIDERS or not isinstance(token, str) or not token:
raise ApiError("provider and token are required", 400)
if not Config.oauth_provider_enabled(provider):
raise _disabled()
from ..services.rate_limit import check as ratelimit
client_ip = request.remote_addr or "?"
if not ratelimit("oauth:ip", client_ip, limit=15, window=300):
raise ApiError("too many attempts, try again later", 429)
# Server-side token validation only; identity comes from the provider.
try:
if provider == "google":
email, provider_sub, display_name = oauth_svc.validate_google_token(token)
else: # facebook
email, provider_sub, display_name = oauth_svc.validate_facebook_token(token)
except oauth_svc.OAuthError:
raise ApiError("social login failed", 401)
if not ratelimit("oauth:email", email, limit=8, window=300):
raise ApiError("too many attempts, try again later", 429)
store = _store()
try:
if (
not isinstance(provider_sub, str)
or not provider_sub.strip()
or len(provider_sub) > 255
):
raise AuthError("invalid oauth identity")
provider_sub = provider_sub.strip()
with store.users.collection_lock():
user = _bound_user(store, provider, provider_sub)
if user is None:
if store.by_email(email) is not None:
raise AuthError("explicit account linking required")
user = _ensure_default_org_user(
store, provider, provider_sub, email, display_name
)
if user.get("active") is not True:
raise AuthError("oauth disabled")
existing_org = store.get_org_or_none(user.get("org_id"))
if existing_org is None or existing_org.get("active") is not True:
raise AuthError("oauth disabled")
jwt = store.issue_token(user)
except AuthError:
# Generic to the client; never leak why (disabled/seats/invalid state).
raise ApiError("social login failed", 401)
except (OSError, TypeError, ValueError, UnicodeError, OverflowError) as exc:
raise internal_error("oauth exchange failed", exc, 503)
public_user = store.public_user(user)
return jsonify(
{
"token": jwt,
"user": public_user,
"must_setup": public_user["must_setup"],
}
)