Skip to content

Commit

Permalink
add missing cooke clear case
Browse files Browse the repository at this point in the history
  • Loading branch information
dauglyon committed Feb 26, 2024
1 parent 96ca232 commit d1c816a
Showing 1 changed file with 33 additions and 8 deletions.
41 changes: 33 additions & 8 deletions src/features/auth/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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] =
Expand All @@ -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),
Expand All @@ -76,7 +101,7 @@ export const useTokenCookie = (
if (backupCookieName) clearBackupCookieToken();
}
}, [
initialized,
appAuthInitialized,
token,
expires,
setCookieToken,
Expand All @@ -89,7 +114,7 @@ export const useTokenCookie = (
useEffect(() => {
if (
Boolean(backupCookieName) &&
initialized &&
appAuthInitialized &&
token &&
backupCookieToken !== token
) {
Expand All @@ -108,7 +133,7 @@ export const useTokenCookie = (
backupCookieName,
backupCookieToken,
expires,
initialized,
appAuthInitialized,
setBackupCookieToken,
token,
]);
Expand Down

0 comments on commit d1c816a

Please sign in to comment.