"""Admin routes: user provisioning + role management (no self-registration).""" from __future__ import annotations from flask import Blueprint, jsonify, request from ..auth.users import AuthError from ..config import Config from .helpers import ApiError, current_user, require_auth, require_roles admin_bp = Blueprint("admin", __name__) def _store(): from flask import current_app return current_app.extensions["user_store"] def _log_audit(action: str, subject: str, *, detail: dict | None = None) -> None: """Append a line to the audit log (sensitive platform actions).""" import json import time from ..config import Config entry = { "ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "actor": (current_user() or {}).get("username") or (current_user() or {}).get("id"), "action": action, "subject": subject, "detail": detail or {}, } try: log_dir = Config.DATA_DIR / "audit" log_dir.mkdir(parents=True, exist_ok=True) with open(log_dir / "audit.jsonl", "a", encoding="utf-8") as fh: fh.write(json.dumps(entry, ensure_ascii=False) + "\n") except Exception: # Audit logging must never break the request. pass @admin_bp.get("/orgs") @require_auth @require_roles("admin") def list_orgs(): """Platform view: all organizations (super_admin). Admin sees only their own.""" actor = current_user() if actor.get("role") == "super_admin": orgs = list(_store().orgs.all()) return jsonify({"orgs": orgs}) # plain admin: only their own org org = _store().orgs.get_or_none(actor.get("org_id")) return jsonify({"orgs": [org] if org else []}) @admin_bp.patch("/orgs/") @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") def create_user(): """Create a user + provision a password (invite). Admin or super-admin only.""" data = request.get_json(silent=True) or {} name = (data.get("name") or "").strip() username = (data.get("username") or data.get("email") or "").strip().lower() password = data.get("password") or "" role = (data.get("role") or "user").strip() org_id = (data.get("org_id") or current_user().get("org_id") or "org-default").strip() if not username or not password: raise ApiError("username and password are required") if role not in Config.ROLES: raise ApiError(f"invalid role: {role}") # Only super_admin can create another admin/super_admin actor_role = current_user().get("role") if role in ("admin", "super_admin") and actor_role != "super_admin": raise ApiError("only super_admin can grant admin roles", 403) # Multi-tenant: provisioning a brand-new org (super_admin only). The created user # becomes that org's first admin (tenant owner). Everything is isolated per org. new_org = bool(data.get("new_org")) if new_org: if actor_role != "super_admin": raise ApiError("only super_admin can create a new organization", 403) if role != "admin": raise ApiError("new-org first user must be role=admin", 400) org = _store().create_org(name or username) org_id = org["id"] _log_audit("org.create", org_id, detail={"name": name or username}) try: user = _store().create_user( org_id=org_id, username=username, password=password, name=name, role=role ) except AuthError as exc: raise ApiError(str(exc)) return jsonify({"user": _store().public_user(user), "org_id": org_id}), 201 @admin_bp.get("/users") @require_auth @require_roles("admin") def list_users(): actor = current_user() if actor.get("role") == "super_admin": users = _store().list_users() else: users = _store().list_users(org_id=actor.get("org_id")) return jsonify({"users": users}) @admin_bp.put("/users/") @require_auth @require_roles("admin") def update_user(username: str): data = request.get_json(silent=True) or {} username = username.strip().lower() actor = current_user() target = _store().get_user_or_none(username) if not target: raise ApiError("user not found", 404) # Role changes / admin-modification restricted to super_admin if "role" in data: role = (data.get("role") or "").strip() if role not in Config.ROLES: raise ApiError(f"invalid role: {role}") if actor.get("role") != "super_admin": raise ApiError("only super_admin can change roles") _store().set_role(username, role) if role == "super_admin": _log_audit("user.promote_super_admin", username) if "active" in data: if actor.get("role") != "super_admin": raise ApiError("only super_admin can activate/deactivate users") _store().set_active(username, bool(data.get("active"))) if "password" in data and data.get("password"): _store().set_password(username, data.get("password")) if "email" in data: try: _store().set_email(username, data.get("email")) except AuthError as exc: raise ApiError(str(exc)) return jsonify({"user": _store().public_user(_store().get_user(username))})