'use client'; import { ReactNode, useEffect } from 'react'; import useSWR from 'swr'; import { useAuth } from '@/services/hooks/useAuth'; import { httpClientFetcher, SWRHttpKey } from '@/services/http/client'; import { isResponseError, isResponseSuccess } from '@/lib/api-helper'; import { BaseApiResponse, GetMeResponse } from '@/types/api/api-general'; import { AxiosError } from 'axios'; import { redirectToSSO } from '@/lib/auth-helper'; interface RequireAuthProps { children?: ReactNode; } const RequireAuth = ({ children }: RequireAuthProps) => { const { user, setUser, setIsLoadingUser } = useAuth(); const { data: userResponse, isLoading: isLoadingUserResponse, error: userErrorResponse, } = useSWR< GetMeResponse & { ok?: boolean }, AxiosError, SWRHttpKey >('/sso/userinfo', httpClientFetcher, { shouldRetryOnError: false, // refresh every 13 minutes refreshInterval: 13 * 60 * 1000, }); useEffect(() => { if (isResponseSuccess(userResponse)) { setUser(userResponse.data); } }, [userResponse, setUser]); // Explicitly handle 401 redirect from the component level useEffect(() => { if ( isResponseError(userResponse) && userErrorResponse?.response?.status === 401 ) { // Clear cache to prevent stale data from rendering children // mutate('/sso/userinfo', undefined, { revalidate: false }); // Optional: if using global mutate setUser(undefined); redirectToSSO(); } }, [userErrorResponse, setUser, userResponse]); useEffect(() => { setIsLoadingUser(isLoadingUserResponse); }, [isLoadingUserResponse]); if ( (isLoadingUserResponse && !userResponse && !userErrorResponse) || (!userResponse && !userErrorResponse) ) { return (
); } if (userErrorResponse) { return (

Authentication Failed

Please try refreshing the page or contact support if the problem persists.

); } return <>{isResponseSuccess(userResponse) && user && children}; }; export default RequireAuth;