fix: prevent admin page reload redirect to dashboard

Wait for admin role check to complete before setting loading to false.
This prevents race condition where:
1. authLoading becomes false after session loads
2. isAdmin is still false (async check in progress)
3. Page redirects to /dashboard before isAdmin is set to true

Now loading stays true until BOTH session and admin role are loaded,
ensuring admin pages don't redirect on reload.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
dwindown
2025-12-27 23:55:46 +07:00
parent 79e1bd82fc
commit 0e3a45cfe2

View File

@@ -31,11 +31,14 @@ export function AuthProvider({ children }: { children: ReactNode }) {
setUser(session?.user ?? null);
if (session?.user) {
checkAdminRole(session.user.id);
// Wait for admin role check before setting loading to false
checkAdminRole(session.user.id).then(() => {
if (mounted) setLoading(false);
});
} else {
// No session, set loading to false immediately
if (mounted) setLoading(false);
}
// Only set loading to false after initial session is loaded
setLoading(false);
});
// Then listen for auth state changes
@@ -47,13 +50,15 @@ export function AuthProvider({ children }: { children: ReactNode }) {
setUser(session?.user ?? null);
if (session?.user) {
checkAdminRole(session.user.id);
// Wait for admin role check
checkAdminRole(session.user.id).then(() => {
if (mounted) setLoading(false);
});
} else {
setIsAdmin(false);
// No session, set loading to false immediately
if (mounted) setLoading(false);
}
// Ensure loading is false after auth state changes
setLoading(false);
}
);
@@ -70,8 +75,9 @@ export function AuthProvider({ children }: { children: ReactNode }) {
.eq('user_id', userId)
.eq('role', 'admin')
.maybeSingle();
setIsAdmin(!!data);
return !!data; // Return the result
};
const signIn = async (email: string, password: string) => {