diff --git a/src/frontend/src/authStatusCheck.ts b/src/frontend/src/authStatusCheck.ts new file mode 100644 index 000000000..ef37ba1a6 --- /dev/null +++ b/src/frontend/src/authStatusCheck.ts @@ -0,0 +1,33 @@ +import { API_URL } from './config'; +import { actions } from './features/auth/store'; +import { type AppStore } from './store'; + +const sleep = async (timeout: number): Promise => { + await new Promise(resolve => { + setTimeout(() => { + resolve({}); + }, timeout); + }); +}; + +export const initAuthUserState = async (store: AppStore): Promise => { + let retryCount = 0; + let waitInterval = 5000; + let response: Response; + + do { + response = await fetch(`${API_URL}/api/v1/auth/status`); + + if (response.ok) { + store.dispatch(actions.signIn()); + return; + } + + await sleep(waitInterval); + + retryCount++; + waitInterval *= 2; + } while (retryCount < 4); + + store.dispatch(actions.signOut()); +}; diff --git a/src/frontend/src/features/auth/hooks/useAuth.ts b/src/frontend/src/features/auth/hooks/useAuth.ts index 177d42c51..f9dce37a0 100644 --- a/src/frontend/src/features/auth/hooks/useAuth.ts +++ b/src/frontend/src/features/auth/hooks/useAuth.ts @@ -22,13 +22,7 @@ interface UseAuthHookResult { export default function useAuth(): UseAuthHookResult { const user = useAppSelector(state => state.auth.user); const dispatch = useAppDispatch(); - - const { refetch, isFetching } = authApi.useGetStatusQuery( - {}, - { - skip: !!user, - }, - ); + const [getAuthStatus, getAuthStatusRequest] = authApi.useLazyGetStatusQuery(); const signIn = useCallback(() => { dispatch(actions.signIn()); @@ -60,16 +54,16 @@ export default function useAuth(): UseAuthHookResult { }, [signOut]); const completeLogin = useCallback(() => { - void refetch(); - }, [refetch]); + void getAuthStatus({}); + }, [getAuthStatus]); const completeLogout = useCallback(() => { - void refetch(); - }, [refetch]); + void getAuthStatus({}); + }, [getAuthStatus]); return { user, - isLoggingIn: isFetching, + isLoggingIn: getAuthStatusRequest.isFetching, login, logout, completeLogin, diff --git a/src/frontend/src/index.tsx b/src/frontend/src/index.tsx index fff8eaa7a..8b94911f9 100644 --- a/src/frontend/src/index.tsx +++ b/src/frontend/src/index.tsx @@ -3,7 +3,8 @@ import { initBrowserMockApi } from 'tests/mockApi'; import { createRoot } from 'react-dom/client'; import App from './App'; import AppProvider from './AppProvider'; -import { GOOGLE_ANALYTICS_ENABLED, MSW_ENABLED } from './config'; +import { initAuthUserState } from './authStatusCheck'; +import { FAKE_AUTH_ENABLED, GOOGLE_ANALYTICS_ENABLED, MSW_ENABLED } from './config'; import { initGoogleAnalytics } from './googleAnalytics'; import store from './store'; @@ -16,6 +17,10 @@ void (async () => { initGoogleAnalytics(); } + if (!FAKE_AUTH_ENABLED) { + await initAuthUserState(store); + } + const container = document.getElementById('root') as HTMLElement; const root = createRoot(container);