fix: block race condition causing logout during impersonation handoff
All checks were successful
Build and Deploy / build-and-push (push) Successful in 1m31s

- Introduced isReloadingForImpersonation flag to temporarily disable the logout function while tokens are being swapped before the hard reload.
This commit is contained in:
Cauê Faleiros
2026-03-11 15:49:03 -03:00
parent bf157687d4
commit 1d49161a05

View File

@@ -357,7 +357,11 @@ export const deleteTenant = async (id: string): Promise<boolean> => {
// --- 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<any> => {
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;
}