"""Super Admin bootstrap — admin-only user creation. Creates the initial super-admin user via Supabase Auth admin API. Reads credentials from env vars only: SUPERADMIN_EMAIL [required] SUPERADMIN_PASSWORD [required at first run; rotate via Supabase later] If either is missing the bootstrap is skipped (in dev) or aborts (in prod when explicitly invoked). Hardcoded fallback credentials have been removed to prevent accidental exposure in production environments. """ from __future__ import annotations from typing import Optional from src.api.supabase_client import get_db from src.utils.env import env_str from src.utils.logging import get_logger logger = get_logger(__name__) def _read_credentials() -> tuple[Optional[str], Optional[str]]: email = env_str("SUPERADMIN_EMAIL", "").strip() or None password = env_str("SUPERADMIN_PASSWORD", "").strip() or None return email, password def create_super_admin() -> bool: """Create super admin user if it doesn't exist. Returns True if the admin already existed or was created successfully, False otherwise. Never raises. """ email, password = _read_credentials() if not email or not password: logger.warning( "admin_bootstrap: skipped — SUPERADMIN_EMAIL/SUPERADMIN_PASSWORD not set" ) return False try: db = get_db() # Probe existence via signin attempt. We don't keep the session. try: db.auth.sign_in_with_password({"email": email, "password": password}) logger.info("admin_bootstrap: super admin already exists", extra={"email": email}) return True except Exception: # Not signed in — create it. auth_response = db.auth.admin.create_user( { "email": email, "password": password, "email_confirm": True, "user_metadata": {"full_name": "Super Admin"}, "app_metadata": {"role": "admin"}, } ) if auth_response.user: db.table("profiles").update( {"role": "admin", "full_name": "Super Admin"} ).eq("id", auth_response.user.id).execute() logger.info( "admin_bootstrap: super admin created", extra={"email": email, "user_id": auth_response.user.id}, ) return True logger.error("admin_bootstrap: create_user returned no user", extra={"email": email}) return False except Exception: logger.exception("admin_bootstrap: failed to provision super admin") return False def setup_admin_only_mode() -> None: """Idempotent setup entry-point for the admin-only mode. Intended to be invoked from a maintenance script (``python -m src.api.admin_setup``) — not at every app startup. """ logger.info("admin_bootstrap: starting admin-only mode setup") email, password = _read_credentials() if not email or not password: raise RuntimeError( "admin_bootstrap: SUPERADMIN_EMAIL and SUPERADMIN_PASSWORD must be set" ) ok = create_super_admin() if ok: logger.info( "admin_bootstrap: setup complete — public registration disabled", extra={"login_email": email}, ) else: raise RuntimeError("admin_bootstrap: provisioning failed (check logs for details)") if __name__ == "__main__": setup_admin_only_mode()