⚙️ Atualização local para GPI - Sync via Antigravity
This commit is contained in:
@@ -1,8 +1,7 @@
|
||||
import React, { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useUser, useOrganization } from '@clerk/clerk-react';
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import type { AppUser } from '../types';
|
||||
import { AuthContext } from './AuthContextType';
|
||||
import { setApiClerkUserId, setApiOrganizationId, getBaseUrl } from '../services/api';
|
||||
import api, { getBaseUrl, setApiOrganizationId } from '../services/api';
|
||||
|
||||
const API_URL = getBaseUrl();
|
||||
|
||||
@@ -11,119 +10,57 @@ interface AuthProviderProps {
|
||||
}
|
||||
|
||||
export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
|
||||
const { user, isLoaded } = useUser();
|
||||
const { organization, membership } = useOrganization();
|
||||
const [appUser, setAppUser] = useState<AppUser | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const lastContextRef = useRef<{ clerkId?: string, orgId?: string | null }>({});
|
||||
|
||||
// Set the clerk user ID and organization ID for the API interceptor
|
||||
useEffect(() => {
|
||||
setApiClerkUserId(user?.id || null);
|
||||
setApiOrganizationId(organization?.id || null);
|
||||
}, [user?.id, organization?.id]);
|
||||
const logout = useCallback(() => {
|
||||
localStorage.removeItem('gpi_token');
|
||||
setAppUser(null);
|
||||
setApiOrganizationId(null);
|
||||
window.location.href = '/login';
|
||||
}, []);
|
||||
|
||||
const syncUser = useCallback(async () => {
|
||||
if (!user) {
|
||||
const fetchMe = useCallback(async () => {
|
||||
const token = localStorage.getItem('gpi_token');
|
||||
if (!token) {
|
||||
setAppUser(null);
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Only set loading if the context has changed (new user or new organization)
|
||||
// This prevents unmounting/remounting components on window focus revalidations
|
||||
const isSameContext =
|
||||
lastContextRef.current.clerkId === user.id &&
|
||||
lastContextRef.current.orgId === (organization?.id || null);
|
||||
|
||||
if (!isSameContext) {
|
||||
setIsLoading(true);
|
||||
}
|
||||
setError(null);
|
||||
|
||||
// Sync user with backend, including organization context
|
||||
const response = await fetch(`${API_URL}/users/sync`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-clerk-user-id': user.id,
|
||||
...(organization?.id && { 'x-organization-id': organization.id }),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
clerkId: user.id,
|
||||
email: user.primaryEmailAddress?.emailAddress || '',
|
||||
name: user.fullName || user.firstName || 'Usuário',
|
||||
organizationId: organization?.id || null,
|
||||
clerkRole: membership?.role || null, // org:admin, org:member, etc.
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const data = await response.json();
|
||||
if (response.status === 403 && data.error?.includes('bloqueada')) {
|
||||
setError('Sua conta foi bloqueada. Entre em contato com o administrador.');
|
||||
setAppUser(null);
|
||||
return;
|
||||
}
|
||||
throw new Error('Falha ao sincronizar usuário');
|
||||
}
|
||||
|
||||
const syncedUser = await response.json();
|
||||
// Use organizationRole if available (per-org role), otherwise fall back to global role
|
||||
const effectiveRole = syncedUser.organizationRole || syncedUser.role || 'guest';
|
||||
setIsLoading(true);
|
||||
const response = await api.get('/auth/me');
|
||||
const userData = response.data;
|
||||
|
||||
setAppUser({
|
||||
...syncedUser,
|
||||
id: syncedUser._id || syncedUser.id,
|
||||
role: effectiveRole, // Override with organization-specific role
|
||||
...userData,
|
||||
id: userData._id || userData.id
|
||||
});
|
||||
|
||||
// Update last context ref
|
||||
lastContextRef.current = { clerkId: user.id, orgId: organization?.id || null };
|
||||
} catch (err) {
|
||||
console.error('Error syncing user:', err);
|
||||
setError('Erro ao carregar dados do usuário');
|
||||
|
||||
if (userData.organizationId) {
|
||||
setApiOrganizationId(userData.organizationId);
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.error('Error fetching current user:', err);
|
||||
if (err.response?.status === 401) {
|
||||
logout();
|
||||
} else {
|
||||
setError('Erro ao carregar dados do usuário');
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [user, organization?.id, membership?.role]);
|
||||
}, [logout]);
|
||||
|
||||
const refetchUser = useCallback(async () => {
|
||||
if (!user) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/users/me`, {
|
||||
headers: {
|
||||
'x-clerk-user-id': user.id,
|
||||
...(organization?.id && { 'x-organization-id': organization.id }),
|
||||
},
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const userData = await response.json();
|
||||
const effectiveRole = userData.organizationRole || userData.role || 'guest';
|
||||
setAppUser({
|
||||
...userData,
|
||||
id: userData._id || userData.id,
|
||||
role: effectiveRole,
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error refetching user:', err);
|
||||
}
|
||||
}, [user, organization?.id]);
|
||||
|
||||
// Re-sync when organization changes
|
||||
useEffect(() => {
|
||||
if (isLoaded && user) {
|
||||
syncUser();
|
||||
}
|
||||
}, [isLoaded, user, organization?.id, syncUser]);
|
||||
fetchMe();
|
||||
}, [fetchMe]);
|
||||
|
||||
const isDeveloper = useCallback(() => {
|
||||
return user?.primaryEmailAddress?.emailAddress === 'admtracksteel@gmail.com';
|
||||
}, [user]);
|
||||
return appUser?.email === 'admtracksteel@gmail.com';
|
||||
}, [appUser]);
|
||||
|
||||
const isAdmin = useCallback(() => appUser?.role === 'admin' || isDeveloper(), [appUser, isDeveloper]);
|
||||
const isUser = useCallback(() => appUser?.role === 'user' || isAdmin(), [appUser, isAdmin]);
|
||||
@@ -135,14 +72,15 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
|
||||
value={{
|
||||
appUser,
|
||||
isLoading,
|
||||
isSignedIn: !!user,
|
||||
isSignedIn: !!appUser,
|
||||
error,
|
||||
isAdmin,
|
||||
isUser,
|
||||
isGuest,
|
||||
isDeveloper,
|
||||
canEdit,
|
||||
refetchUser,
|
||||
refetchUser: fetchMe,
|
||||
logout, // Added logout to context
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
|
||||
Reference in New Issue
Block a user