From 1d49161a05e584d1d7715a323ce500e81ed5c345 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Wed, 11 Mar 2026 15:49:03 -0300 Subject: [PATCH] fix: block race condition causing logout during impersonation handoff - Introduced isReloadingForImpersonation flag to temporarily disable the logout function while tokens are being swapped before the hard reload. --- services/dataService.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/services/dataService.ts b/services/dataService.ts index 6da81c4..1bf592a 100644 --- a/services/dataService.ts +++ b/services/dataService.ts @@ -357,7 +357,11 @@ export const deleteTenant = async (id: string): Promise => { // --- Auth Functions --- +// Flag to prevent background fetches from throwing 401 and logging out during impersonation handoffs +export let isReloadingForImpersonation = false; + export const logout = () => { + if (isReloadingForImpersonation) return; // Prevent logout if we are just switching tokens localStorage.removeItem('ctms_token'); localStorage.removeItem('ctms_user_id'); localStorage.removeItem('ctms_tenant_id'); @@ -401,6 +405,8 @@ export const impersonateTenant = async (tenantId: string): Promise => { throw new Error(errorData.error || 'Erro ao assumir identidade'); } + isReloadingForImpersonation = true; // Block logouts + const data = await response.json(); const oldToken = localStorage.getItem('ctms_token'); if (oldToken) { @@ -421,6 +427,8 @@ export const returnToSuperAdmin = (): boolean => { const superAdminToken = localStorage.getItem('ctms_super_admin_token'); if (superAdminToken) { try { + isReloadingForImpersonation = true; // Block logouts + // Correctly decode Base64Url JWT payload with proper padding const base64Url = superAdminToken.split('.')[1]; let base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/'); @@ -443,6 +451,7 @@ export const returnToSuperAdmin = (): boolean => { window.location.reload(); return true; } catch (e) { + isReloadingForImpersonation = false; console.error("Failed to restore super admin token", e); return false; }