fix: resolve login persistence bug and aggressive logout on network blips
All checks were successful
Build and Deploy / build-and-push (push) Successful in 1m58s
All checks were successful
Build and Deploy / build-and-push (push) Successful in 1m58s
- Updated Login.tsx to automatically redirect users to the dashboard if a valid token is already present in localStorage. - Refactored getUserById to properly throw server/network errors instead of silently returning undefined. - Updated AuthGuard in App.tsx to gracefully handle network errors without destroying the user's valid localStorage tokens.
This commit is contained in:
22
App.tsx
22
App.tsx
@@ -35,15 +35,27 @@ const AuthGuard: React.FC<{ children: React.ReactNode, roles?: string[] }> = ({
|
||||
|
||||
try {
|
||||
const fetchedUser = await getUserById(storedUserId);
|
||||
if (fetchedUser && fetchedUser.status === 'active') {
|
||||
setUser(fetchedUser);
|
||||
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", err);
|
||||
logout();
|
||||
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);
|
||||
@@ -53,7 +65,7 @@ const AuthGuard: React.FC<{ children: React.ReactNode, roles?: string[] }> = ({
|
||||
}, [location.pathname]);
|
||||
|
||||
if (loading) {
|
||||
return <div className="flex h-screen items-center justify-center bg-slate-50 text-slate-400">Carregando...</div>;
|
||||
return <div className="flex h-screen items-center justify-center bg-zinc-50 dark:bg-zinc-950 text-zinc-400">Carregando...</div>;
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
|
||||
Reference in New Issue
Block a user