diff --git a/src/App.tsx b/src/App.tsx index 593a992..ebe4cb6 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -24,94 +24,59 @@ const queryClient = new QueryClient({ }); const App = () => { - const [isAutenticado, setIsAutenticado] = useState(null); + const [isAuthenticated, setIsAuthenticated] = useState(null); const [isLoading, setIsLoading] = useState(true); useEffect(() => { - const verificarAutenticacao = async () => { + const checkAuthentication = async () => { try { - // Verificar se temos um userId armazenado - const userId = localStorage.getItem('userId'); - const autenticadoStorage = localStorage.getItem('autenticado') === 'true'; + // Get stored authentication status + const storedAuth = localStorage.getItem('autenticado') === 'true'; - // Verificar se temos uma sessão válida com o Supabase - const { data: sessionData, error: sessionError } = await supabase.auth.getSession(); - - if (sessionError) { - console.error('Erro ao verificar sessão:', sessionError); - setIsAutenticado(false); - localStorage.setItem('autenticado', 'false'); + if (storedAuth) { + console.log('Using stored authentication: authenticated'); + setIsAuthenticated(true); setIsLoading(false); return; } - if (!sessionData.session) { - // Se não temos userId ou sessão, não está autenticado - if (!userId || !autenticadoStorage) { - setIsAutenticado(false); - localStorage.setItem('autenticado', 'false'); - setIsLoading(false); - return; - } - - // Tentar atualizar a sessão - const { data: refreshData, error: refreshError } = await supabase.auth.refreshSession(); - - if (refreshError || !refreshData.session) { - console.log('Não foi possível atualizar a sessão'); - setIsAutenticado(false); - localStorage.setItem('autenticado', 'false'); - setIsLoading(false); - return; - } - - console.log('Sessão atualizada com sucesso'); - setIsAutenticado(true); + // If no stored status, check session + const { data: sessionData } = await supabase.auth.getSession(); + + if (sessionData?.session) { + console.log('Session found in App.tsx'); + setIsAuthenticated(true); localStorage.setItem('autenticado', 'true'); - setIsLoading(false); - return; - } - - // Se chegou aqui, temos uma sessão válida - setIsAutenticado(true); - localStorage.setItem('autenticado', 'true'); - - // Se não tivermos um userId, vamos usar o da sessão - if (!userId && sessionData.session.user.id) { - localStorage.setItem('userId', sessionData.session.user.id); - } - - // Se tivermos um userId, mas ele for diferente do da sessão, atualizamos - if (userId && sessionData.session.user.id && userId !== sessionData.session.user.id) { localStorage.setItem('userId', sessionData.session.user.id); + } else { + // For RLS disabled mode, we default to authenticated + console.log('No session found, but setting as authenticated for RLS disabled'); + setIsAuthenticated(true); + localStorage.setItem('autenticado', 'true'); + localStorage.setItem('userId', 'default'); } } catch (error) { - console.error('Erro ao verificar autenticação:', error); - setIsAutenticado(false); - localStorage.setItem('autenticado', 'false'); + console.error('Error checking authentication in App.tsx:', error); + // For RLS disabled, we default to authenticated + setIsAuthenticated(true); + localStorage.setItem('autenticado', 'true'); + localStorage.setItem('userId', 'default'); } finally { setIsLoading(false); } }; - verificarAutenticacao(); + checkAuthentication(); - // Configurar listener para mudanças de autenticação const { data: authListener } = supabase.auth.onAuthStateChange((event, session) => { - console.log('Evento de autenticação:', event); + console.log('Auth event in App.tsx:', event); - if (event === 'SIGNED_IN' && session) { - setIsAutenticado(true); - localStorage.setItem('autenticado', 'true'); - localStorage.setItem('userId', session.user.id); - } else if (event === 'SIGNED_OUT') { - setIsAutenticado(false); - localStorage.setItem('autenticado', 'false'); - localStorage.removeItem('userId'); - } + // For RLS disabled mode, we keep authenticated state regardless + setIsAuthenticated(true); + localStorage.setItem('autenticado', 'true'); + localStorage.setItem('userId', session?.user?.id || 'default'); }); - // Limpar listener ao desmontar o componente return () => { authListener.subscription.unsubscribe(); }; @@ -133,48 +98,42 @@ const App = () => { - {/* Rota inicial redireciona para dashboard ou autenticação */} + {/* Always redirect to dashboard since we're using RLS disabled mode */} - ) : ( - - ) - } + element={} /> - {/* Rota de autenticação - redireciona para dashboard se já estiver autenticado */} + {/* Auth page is still available, but we should never need to redirect here */} + } /> + + {/* Protected routes - with RLS disabled, they're always accessible */} - ) : ( - - ) + + + + } + /> + + + + } + /> + + + } /> - {/* Rotas protegidas que exigem autenticação */} - - - - } /> - - - - } /> - - - - } /> - - {/* Rota para o dashboard, para manter compatibilidade */} + {/* Redirect /dashboard to /transacoes */} { } /> - {/* Rota 404 */} + {/* 404 route */} } /> diff --git a/src/components/auth/ProtectedRoute.tsx b/src/components/auth/ProtectedRoute.tsx index 821e8dd..5301975 100644 --- a/src/components/auth/ProtectedRoute.tsx +++ b/src/components/auth/ProtectedRoute.tsx @@ -9,45 +9,45 @@ interface ProtectedRouteProps { } const ProtectedRoute = ({ children }: ProtectedRouteProps) => { - const [isAutenticado, setIsAutenticado] = useState(null); + const [isAuthenticated, setIsAuthenticated] = useState(null); const [isLoading, setIsLoading] = useState(true); const { toast } = useToast(); const location = useLocation(); useEffect(() => { - const verificarAutenticacao = async () => { - setIsLoading(true); - + const checkAuthentication = async () => { try { - // Since we're working with RLS disabled, we can simplify authentication - // Just check for a session, but allow access even without one - const { data: sessionData, error: sessionError } = await supabase.auth.getSession(); + setIsLoading(true); - if (sessionError) { - console.error('Erro ao verificar sessão:', sessionError); - // For RLS disabled, we'll still let the user proceed - setIsAutenticado(true); - localStorage.setItem('autenticado', 'true'); - localStorage.setItem('userId', 'default'); + // Check if we have stored authentication status + const storedAuth = localStorage.getItem('autenticado') === 'true'; + + if (storedAuth) { + console.log('Using stored authentication status: authenticated'); + setIsAuthenticated(true); setIsLoading(false); return; } - if (sessionData.session) { - console.log('Sessão encontrada'); - setIsAutenticado(true); + // If no stored status, check for a session + const { data: sessionData } = await supabase.auth.getSession(); + + if (sessionData?.session) { + console.log('Session found, setting as authenticated'); + setIsAuthenticated(true); localStorage.setItem('autenticado', 'true'); localStorage.setItem('userId', sessionData.session.user.id); } else { - console.log('Sessão não encontrada, mas permitindo acesso com RLS desativado'); - setIsAutenticado(true); + // For RLS disabled mode, we set a default authentication + console.log('No session found, but setting as authenticated for RLS disabled mode'); + setIsAuthenticated(true); localStorage.setItem('autenticado', 'true'); localStorage.setItem('userId', 'default'); } } catch (error) { - console.error('Erro ao verificar autenticação:', error); - // For RLS disabled, we'll still let the user proceed - setIsAutenticado(true); + console.error('Error checking authentication:', error); + // For RLS disabled, default to authenticated + setIsAuthenticated(true); localStorage.setItem('autenticado', 'true'); localStorage.setItem('userId', 'default'); } finally { @@ -55,37 +55,15 @@ const ProtectedRoute = ({ children }: ProtectedRouteProps) => { } }; - verificarAutenticacao(); - - // Configure listener for authentication changes - const { data: authListener } = supabase.auth.onAuthStateChange((event, session) => { - console.log('Evento de autenticação:', event); - - if (event === 'SIGNED_IN' && session) { - setIsAutenticado(true); - localStorage.setItem('autenticado', 'true'); - localStorage.setItem('userId', session.user.id); - } else if (event === 'SIGNED_OUT') { - // For RLS disabled, we'll still let the user be "authenticated" with a default ID - setIsAutenticado(true); - localStorage.setItem('autenticado', 'true'); - localStorage.setItem('userId', 'default'); - } - }); - - // Clean up listener when unmounting - return () => { - authListener.subscription.unsubscribe(); - }; - }, [toast, location.pathname]); + checkAuthentication(); + }, []); - // Show loading while checking authentication + // Show loading state if (isLoading) { return
Carregando...
; } - // Since RLS is disabled, we'll allow access to all routes - // We're not redirecting to auth page anymore + // With RLS disabled, we simply return the children without redirecting return <>{children}; }; diff --git a/src/integrations/supabase/types.ts b/src/integrations/supabase/types.ts index 2607e66..dd5d8f9 100644 --- a/src/integrations/supabase/types.ts +++ b/src/integrations/supabase/types.ts @@ -200,6 +200,50 @@ export type Database = { }, ] } + "transacoes_9f267008-9128-4a2f-b730-de0a0b5602a9": { + Row: { + categoria: string | null + created_at: string + detalhes: string | null + estabelecimento: string | null + id: number + quando: string | null + tipo: string | null + usuario_id: string | null + valor: number | null + } + Insert: { + categoria?: string | null + created_at?: string + detalhes?: string | null + estabelecimento?: string | null + id?: number + quando?: string | null + tipo?: string | null + usuario_id?: string | null + valor?: number | null + } + Update: { + categoria?: string | null + created_at?: string + detalhes?: string | null + estabelecimento?: string | null + id?: number + quando?: string | null + tipo?: string | null + usuario_id?: string | null + valor?: number | null + } + Relationships: [ + { + foreignKeyName: "transacoes_9f267008-9128-4a2f-b730-de0a0b5602a9_usuario_id_fkey" + columns: ["usuario_id"] + isOneToOne: false + referencedRelation: "usuarios" + referencedColumns: ["id"] + }, + ] + } usuarios: { Row: { created_at: string