From d1c816aa38bd43ed59e1374687a7d4fec087db3b Mon Sep 17 00:00:00 2001 From: David Lyon Date: Mon, 26 Feb 2024 12:55:17 -0800 Subject: [PATCH] add missing cooke clear case --- src/features/auth/hooks.ts | 41 ++++++++++++++++++++++++++++++-------- 1 file changed, 33 insertions(+), 8 deletions(-) diff --git a/src/features/auth/hooks.ts b/src/features/auth/hooks.ts index c6e298c5..afe30134 100644 --- a/src/features/auth/hooks.ts +++ b/src/features/auth/hooks.ts @@ -35,7 +35,8 @@ export const useTokenCookie = ( // Pull token from main cookie. If it exists, and differs from state, try it for auth. const [cookieToken, setCookieToken, clearCookieToken] = useCookie(cookieName); - const { isSuccess, isFetching } = useTryAuthFromToken(cookieToken); + const { isSuccess, isFetching, isUninitialized } = + useTryAuthFromToken(cookieToken); // Controls for backupCookie const [backupCookieToken, setBackupCookieToken, clearBackupCookieToken] = @@ -44,21 +45,45 @@ export const useTokenCookie = ( // Pull token, expiration, and init info from auth state const token = useAppSelector(authToken); const expires = useAppSelector(({ auth }) => auth.tokenInfo?.expires); - const initialized = useAppSelector(authInitialized); + const appAuthInitialized = useAppSelector(authInitialized); // Initializes auth for states where useTryAuthFromToken does not set auth useEffect(() => { - if (isFetching || initialized) return; + // If the cookieToken is present but it failed checks and wont be overwritten by a token in state, clear + if ( + cookieToken && + !isUninitialized && + !isFetching && + !isSuccess && + !token + ) { + dispatch(setAuth(null)); + clearCookieToken(); + // clear backup token too, if it exists + if (backupCookieName) clearBackupCookieToken(); + } + if (isFetching || appAuthInitialized) return; if (!cookieToken) { dispatch(setAuth(null)); } else if (!isSuccess) { dispatch(setAuth(null)); } - }, [isFetching, initialized, cookieToken, dispatch, isSuccess]); + }, [ + isFetching, + appAuthInitialized, + cookieToken, + dispatch, + isSuccess, + isUninitialized, + clearCookieToken, + backupCookieName, + clearBackupCookieToken, + token, + ]); // Set the cookie according to the initialized auth state useEffect(() => { - if (!initialized) return; + if (!appAuthInitialized) return; if (token && expires) { setCookieToken(token, { expires: new Date(expires), @@ -76,7 +101,7 @@ export const useTokenCookie = ( if (backupCookieName) clearBackupCookieToken(); } }, [ - initialized, + appAuthInitialized, token, expires, setCookieToken, @@ -89,7 +114,7 @@ export const useTokenCookie = ( useEffect(() => { if ( Boolean(backupCookieName) && - initialized && + appAuthInitialized && token && backupCookieToken !== token ) { @@ -108,7 +133,7 @@ export const useTokenCookie = ( backupCookieName, backupCookieToken, expires, - initialized, + appAuthInitialized, setBackupCookieToken, token, ]);