mirror of
https://gitlab.com/mbugroup/lti-web-client.git
synced 2026-05-25 07:45:47 +00:00
feat(FE-40): create RequireAuth helper component
This commit is contained in:
@@ -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<GetMeResponse & { ok?: boolean }, unknown, SWRHttpKey>(
|
||||||
|
'/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 (
|
||||||
|
<div className='w-full flex flex-row justify-center items-center p-4'>
|
||||||
|
<span className='loading loading-spinner loading-xl' />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return <>{children}</>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default RequireAuth;
|
||||||
Reference in New Issue
Block a user