import React, { useState, useEffect } from 'react'; import { HashRouter as Router, Routes, Route, Navigate, useLocation } from 'react-router-dom'; import { Layout } from './components/Layout'; import { Dashboard } from './pages/Dashboard'; import { UserDetail } from './pages/UserDetail'; import { AttendanceDetail } from './pages/AttendanceDetail'; import { SuperAdmin } from './pages/SuperAdmin'; import { ApiKeys } from './pages/ApiKeys'; import { TeamManagement } from './pages/TeamManagement'; import { Teams } from './pages/Teams'; import { Funnels } from './pages/Funnels'; import { Login } from './pages/Login'; import { ForgotPassword } from './pages/ForgotPassword'; import { ResetPassword } from './pages/ResetPassword'; import { SetupAccount } from './pages/SetupAccount'; import { UserProfile } from './pages/UserProfile'; import { getUserById, logout } from './services/dataService'; import { User } from './types'; const AuthGuard: React.FC<{ children: React.ReactNode, roles?: string[] }> = ({ children, roles }) => { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); const location = useLocation(); useEffect(() => { const checkAuth = async () => { const storedUserId = localStorage.getItem('ctms_user_id'); const storedToken = localStorage.getItem('ctms_token'); if (!storedUserId || !storedToken || storedToken === 'undefined' || storedToken === 'null') { if (storedToken) logout(); // Limpar se for "undefined" string setLoading(false); return; } try { const fetchedUser = await getUserById(storedUserId); if (fetchedUser) { if (fetchedUser.status === 'active') { setUser(fetchedUser); } else { // User explicitly marked inactive or deleted logout(); setUser(null); } } else { // If fetchedUser is undefined but didn't throw, it usually means a 401/403/404 (invalid token or user missing). // However, to be safe against random failures, we should only clear if we are sure it's invalid. // For now, if the token is completely rejected, we log out. logout(); setUser(null); } } catch (err) { console.error("Auth check failed (network/server error):", err); // DO NOT logout() here. If the server is offline or restarting, // we shouldn't wipe the user's local storage tokens. // We just leave the user as null, which will redirect them to login, // but their tokens remain so they can auto-login when the server is back. setUser(null); } finally { setLoading(false); } }; checkAuth(); }, [location.pathname]); if (loading) { return
Carregando...
; } if (!user) { return ; } if (roles && !roles.includes(user.role)) { return ; } // Auto-redirect Super Admins away from the standard dashboard to their specific panel if (location.pathname === '/' && user.role === 'super_admin') { return ; } return {children}; }; const App: React.FC = () => { return ( } /> } /> } /> } /> } /> } /> } /> } /> } /> } /> } /> } /> } /> } /> ); }; export default App;