remocao do clerk

This commit is contained in:
2026-03-14 21:11:43 -03:00
parent c6f69e1c1d
commit 286867739d
13 changed files with 436 additions and 346 deletions

View File

@@ -1,142 +1,108 @@
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useUser, useOrganization } from '@clerk/clerk-react';
import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
import type { AppUser } from '../types';
import { AuthContext } from './AuthContextType';
import { setApiClerkUserId, setApiOrganizationId, getBaseUrl } from '../services/api';
import { setApiToken, setApiOrganizationId, getBaseUrl } from '../services/api';
const API_URL = getBaseUrl();
interface AuthProviderProps {
children: React.ReactNode;
export interface AuthContextType {
appUser: AppUser | null;
isLoading: boolean;
error: string | null;
token: string | null;
login: (token: string, user: AppUser) => void;
logout: () => void;
isAdmin: () => boolean;
isUser: () => boolean;
isGuest: () => boolean;
isDeveloper: () => boolean;
canEdit: () => boolean;
refetchUser: () => Promise<void>;
}
export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
const { user, isLoaded } = useUser();
const { organization, membership } = useOrganization();
export const AuthContext = createContext<AuthContextType | undefined>(undefined);
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [appUser, setAppUser] = useState<AppUser | null>(null);
const [token, setToken] = useState<string | null>(localStorage.getItem('jwt_token'));
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
// Initial load: se tem token, setar no interceptor e buscar dados do usuário
useEffect(() => {
setApiClerkUserId(user?.id || null);
setApiOrganizationId(organization?.id || null);
}, [user?.id, organization?.id]);
const syncUser = useCallback(async () => {
if (!user) {
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';
setAppUser({
...syncedUser,
id: syncedUser._id || syncedUser.id,
role: effectiveRole, // Override with organization-specific role
});
// 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');
} finally {
if (token) {
setApiToken(token);
refetchUser();
} else {
setIsLoading(false);
}
}, [user, organization?.id, membership?.role]);
}, [token]);
const login = useCallback((newToken: string, user: AppUser) => {
localStorage.setItem('jwt_token', newToken);
setToken(newToken);
setAppUser(user);
setApiToken(newToken);
// Se a organização existir, setar o header
if (user.organizationId) {
setApiOrganizationId(user.organizationId);
}
}, []);
const logout = useCallback(() => {
localStorage.removeItem('jwt_token');
setToken(null);
setAppUser(null);
setApiToken(null);
setApiOrganizationId(null);
}, []);
const refetchUser = useCallback(async () => {
if (!user) return;
if (!token) return;
setIsLoading(true);
try {
const response = await fetch(`${API_URL}/users/me`, {
const response = await fetch(`${API_URL}/auth/me`, {
headers: {
'x-clerk-user-id': user.id,
...(organization?.id && { 'x-organization-id': organization.id }),
'Authorization': `Bearer ${token}`
},
});
if (response.ok) {
const userData = await response.json();
const effectiveRole = userData.organizationRole || userData.role || 'guest';
setAppUser({
...userData,
id: userData._id || userData.id,
role: effectiveRole,
});
setAppUser(userData);
if (userData.organizationId) {
setApiOrganizationId(userData.organizationId);
}
} else {
// Token inválido ou expirado
logout();
}
} catch (err) {
console.error('Error refetching user:', err);
setError('Falha na comunicação de autenticação.');
} finally {
setIsLoading(false);
}
}, [user, organization?.id]);
// Re-sync when organization changes
useEffect(() => {
if (isLoaded && user) {
syncUser();
}
}, [isLoaded, user, organization?.id, syncUser]);
}, [token, logout]);
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]);
const isGuest = useCallback(() => appUser?.role === 'guest' && !isDeveloper(), [appUser, isDeveloper]);
const canEdit = useCallback(() => (appUser?.role !== 'guest' && appUser?.role !== undefined) || isDeveloper(), [appUser, isDeveloper]);
const canEdit = useCallback(() => (appUser?.role !== 'guest' && appUser !== null) || isDeveloper(), [appUser, isDeveloper]);
return (
<AuthContext.Provider
value={{
appUser,
isLoading,
isSignedIn: !!user,
error,
token,
login,
logout,
isAdmin,
isUser,
isGuest,
@@ -149,3 +115,11 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
</AuthContext.Provider>
);
};
export const useAuth = () => {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
};