From 6924aef8c47667c5f3a58ec58706e81926805bc4 Mon Sep 17 00:00:00 2001 From: ValdiANS Date: Wed, 1 Oct 2025 14:59:46 +0700 Subject: [PATCH] feat(FE-40): create RequireAuth helper component --- src/components/helper/RequireAuth.tsx | 55 +++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/components/helper/RequireAuth.tsx diff --git a/src/components/helper/RequireAuth.tsx b/src/components/helper/RequireAuth.tsx new file mode 100644 index 00000000..9bc199f9 --- /dev/null +++ b/src/components/helper/RequireAuth.tsx @@ -0,0 +1,55 @@ +'use client'; + +import { ReactNode, useEffect } from 'react'; +import { useRouter } from 'next/navigation'; +import useSWRImmutable from 'swr/immutable'; + +import { useAuth } from '@/services/hooks/useAuth'; +import { httpClientFetcher, SWRHttpKey } from '@/services/http/client'; +import { isResponseSuccess } from '@/lib/api-helper'; +import { GetMeResponse } from '@/types/api/api-general'; + +interface RequireAuthProps { + children?: ReactNode; +} + +const RequireAuth = ({ children }: RequireAuthProps) => { + const router = useRouter(); + const { setUser, setIsLoadingUser } = useAuth(); + + const { data: userResponse, isLoading: isLoadingUserResponse } = + useSWRImmutable( + '/auth/get-me', + httpClientFetcher, + { + shouldRetryOnError: false, + revalidateOnFocus: false, + revalidateOnReconnect: false, + refreshInterval: 0, + } + ); + + useEffect(() => { + setIsLoadingUser(isLoadingUserResponse); + }, [isLoadingUserResponse, setIsLoadingUser]); + + useEffect(() => { + if (isResponseSuccess(userResponse)) { + setUser(userResponse.data); + } else { + router.replace(process.env.NEXT_PUBLIC_SSO_LOGIN_URL as string); + } + }, [userResponse, setIsLoadingUser, setUser]); + + if (isLoadingUserResponse && !userResponse) { + return ( +
+ +
+ ); + } + + return <>{children}; +}; + +export default RequireAuth;