feat(saas): Phase 3 — plan/seats/active model, ToS consent, signed expiring export

P3a: org carries plan/seats/active/created_at; create_user enforces seats + rejects
inactive org; verify blocks login for inactive orgs; PATCH /api/admin/orgs (super_admin)
updates plan/seats/active with audit. Fixed verify swallowing its AuthError.
P3b: export/token issues a 5-min HMAC one-time CSV link; export accepts ?token=.
P3c: setup requires accepted_terms (consent stored); Setup.vue consent checkbox.
All 8 backend suites pass. Rebuilt dist.
This commit is contained in:
Macky
2026-08-09 09:48:55 +07:00
parent 056753e8cb
commit 3d5c81fbd7
36 changed files with 230 additions and 64 deletions

View File

@@ -53,6 +53,37 @@ def list_orgs():
return jsonify({"orgs": [org] if org else []})
@admin_bp.patch("/orgs/<org_id>")
@require_auth
@require_roles("super_admin")
def update_org(org_id: str):
"""Platform: set org plan / seats / active. super_admin only."""
data = request.get_json(silent=True) or {}
org = _store().orgs.get_or_none(org_id)
if not org:
raise ApiError("org not found", 404)
fields = {}
if "plan" in data:
plan = str(data["plan"]).strip()
if plan not in ("trial", "paid", "enterprise"):
raise ApiError("invalid plan (trial/paid/enterprise)")
fields["plan"] = plan
if "seats" in data:
try:
seats = int(data["seats"])
except (TypeError, ValueError):
raise ApiError("invalid seats")
if seats < 1:
raise ApiError("seats must be >= 1")
fields["seats"] = seats
if "active" in data:
fields["active"] = bool(data["active"])
if fields:
_store().orgs.update(org_id, **fields)
_log_audit("org.update", org_id, detail=fields)
return jsonify({"org": _store().orgs.get(org_id)})
@admin_bp.post("/users")
@require_auth
@require_roles("admin")

View File

@@ -43,6 +43,54 @@ def _log_audit(action: str, subject: str, *, detail: dict | None = None) -> None
pass
# Short-lived signed link for CSV export (HMAC-SHA256, expiring). Not the long-lived JWT.
import hmac
import hashlib
import time as _t
_EXPORT_TTL = 300 # 5 minutes
def _sign_export_token(actor: dict) -> str:
from ..config import Config
payload = "{}:{}:{}".format(actor.get("org_id") or "", actor.get("role") or "", int(_t.time()) + _EXPORT_TTL)
sig = hmac.new(Config.SECRET_KEY.encode(), payload.encode(), hashlib.sha256).hexdigest()
return "{}.{}".format(sig, payload)
def _verify_export_token(token: str) -> dict | None:
from ..config import Config
try:
sig, payload = token.split(".", 1)
except (ValueError, AttributeError):
return None
expected = hmac.new(Config.SECRET_KEY.encode(), payload.encode(), hashlib.sha256).hexdigest()
if not hmac.compare_digest(sig, expected):
return None
parts = payload.split(":")
if len(parts) != 3:
return None
org_id, role, exp_s = parts
try:
if int(exp_s) < _t.time():
return None # expired
except ValueError:
return None
return {"org_id": org_id or None, "role": role, "active": True}
@analytics_bp.get("/export/token")
@require_auth
@require_roles("admin")
def export_token():
"""Issue a short-lived signed download link for the CSV export."""
actor = current_user()
token = _sign_export_token(actor)
return jsonify({"token": token, "expires_in": _EXPORT_TTL, "url": f"/api/analytics/export?token={token}"})
def _parse_date_iso(value: str | None, *, end: bool = False) -> str | None:
"""Parse a YYYY-MM-DD into an ISO datetime bound for created_at filtering."""
if not value:
@@ -148,7 +196,11 @@ def export_csv():
from flask import Response, current_app
s = _stores()
actor = current_user()
# Support a short-lived signed link (?token=) OR the normal Bearer JWT.
q_token = request.args.get("token")
actor = _verify_export_token(q_token) if q_token else current_user()
if actor is None:
raise ApiError("invalid or expired export link", 403)
# Tenant: an admin exports only their own org's sessions; super_admin sees all.
export_org = actor.get("org_id") if actor.get("role") != "super_admin" else None
users = {}

View File

@@ -62,10 +62,14 @@ def setup():
username = (data.get("username") or user.get("username") or user.get("id") or "").strip().lower()
email = (data.get("email") or "").strip()
new_password = data.get("password") or ""
# SaaS: consent to Terms/Privacy is required before use.
if not data.get("accepted_terms"):
raise ApiError("you must accept the Terms of Service and Privacy Policy to continue", 400)
if not email or not new_password:
raise ApiError("email and new password are required")
try:
updated = _store().complete_setup(username, email, new_password)
_store().users.update(_store()._norm(username), accepted_terms=True, accepted_terms_at=__import__("time").strftime("%Y-%m-%dT%H:%M:%SZ"))
except AuthError as exc:
raise ApiError(str(exc), 400)
return jsonify({