From e4fe952e069d4d8e92d2aa063987038023d06967 Mon Sep 17 00:00:00 2001 From: Brian O'Kelley Date: Tue, 4 Nov 2025 16:14:16 -0500 Subject: [PATCH] fix: ensure User record creation during OAuth tenant selection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **Problem:** Users with authorized emails/domains could complete OAuth successfully but were blocked from accessing tenant routes due to missing User records. The require_tenant_access decorator checks for User records in the database, but these were never created during the OAuth flow. **Root Cause:** - Tenant authorization checks passed (authorized_emails, authorized_domains) - OAuth callback created session successfully - Tenant selector allowed user to choose tenant - But require_tenant_access() requires User record to exist in DB - No automatic User record creation was happening **Affected User:** jeremie.ratelle@optable.co was authorized at tenant level but had no User record, causing access denial after successful OAuth. **Solution:** 1. Modified select_tenant() to call ensure_user_in_tenant() after tenant selection 2. This creates/updates User record with proper role 3. Created one-time script to fix Jeremie's access immediately **Impact:** - All new OAuth logins will now work correctly - Existing authorized users without User records will get them created on next login 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/admin/blueprints/auth.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/admin/blueprints/auth.py b/src/admin/blueprints/auth.py index ec33e0019..40f1a942b 100644 --- a/src/admin/blueprints/auth.py +++ b/src/admin/blueprints/auth.py @@ -347,6 +347,22 @@ def select_tenant(): # Verify user has access to selected tenant for tenant in session["available_tenants"]: if tenant["tenant_id"] == tenant_id: + # Ensure User record exists in the database + # This is critical for require_tenant_access decorator to work + from src.admin.domain_access import ensure_user_in_tenant + + email = session["user"] + user_name = session.get("user_name", email.split("@")[0].title()) + role = "admin" if tenant["is_admin"] else "viewer" + + try: + ensure_user_in_tenant(email, tenant_id, role=role, name=user_name) + logger.info(f"Ensured User record exists for {email} in tenant {tenant_id}") + except Exception as e: + logger.error(f"Failed to create User record for {email} in tenant {tenant_id}: {e}") + flash("Error setting up user access. Please contact support.", "error") + return redirect(url_for("auth.select_tenant")) + session["tenant_id"] = tenant_id session["is_tenant_admin"] = tenant["is_admin"] session.pop("available_tenants", None) # Clean up