- Cookie SameSite now dynamic: None;Secure when behind HTTPS proxy, Lax otherwise - AuthGuard useEffect no longer overwrites Zustand store with null from background refetch - AuthInitializer: add staleTime 30s Co-Authored-By: Claude <noreply@anthropic.com>
44 lines
1.3 KiB
TypeScript
44 lines
1.3 KiB
TypeScript
import { ReactNode, useEffect } from 'react';
|
|
import { useQuery } from '@tanstack/react-query';
|
|
import { Navigate } from 'react-router-dom';
|
|
import { apiClient } from '@/lib/api-client';
|
|
import { useAuthStore } from '@/store/auth-store';
|
|
|
|
type AuthGuardProps = {
|
|
children: ReactNode;
|
|
requireExpert?: boolean;
|
|
};
|
|
|
|
export function AuthGuard({ children, requireExpert = false }: AuthGuardProps) {
|
|
const user = useAuthStore((state) => state.user);
|
|
const setUser = useAuthStore((state) => state.setUser);
|
|
const query = useQuery({
|
|
queryKey: ['auth', 'me'],
|
|
queryFn: () => apiClient.getMe(),
|
|
staleTime: 30_000,
|
|
});
|
|
|
|
useEffect(() => {
|
|
if (query.data?.user) {
|
|
setUser(query.data.user);
|
|
}
|
|
}, [query.data, setUser]);
|
|
|
|
// Tunjukkan loading hanya jika belum ada user di store
|
|
if (query.isLoading && !user) {
|
|
return <main className="min-h-screen p-8 text-center text-muted-foreground">Memeriksa sesi...</main>;
|
|
}
|
|
|
|
// Cek store dulu, baru query — mencegah redirect saat refetch background
|
|
const currentUser = query.data?.user ?? user;
|
|
if (!currentUser) {
|
|
return <Navigate to="/login" replace />;
|
|
}
|
|
|
|
if (requireExpert && currentUser.role !== 'expert') {
|
|
return <Navigate to="/dashboard" replace />;
|
|
}
|
|
|
|
return <>{children}</>;
|
|
}
|