Skip to content

Commit

Permalink
fix: refactor to catch token error and invalidate session consistently (
Browse files Browse the repository at this point in the history
  • Loading branch information
aversini authored Jul 5, 2024
1 parent f674a54 commit d02c421
Showing 1 changed file with 24 additions and 45 deletions.
69 changes: 24 additions & 45 deletions packages/auth-provider/src/components/AuthProvider/AuthProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,23 @@ export const AuthProvider = ({
[removeIdToken, removeAccessToken, removeNonce, removeRefreshToken],
);

const invalidateAndLogout = useCallback(
async (message: string) => {
removeStateAndLocalStorage(message || EXPIRED_SESSION);
await logoutUser({
idToken,
accessToken,
refreshToken,
clientId,
});
setAuthState((prev) => ({
...prev,
isLoading: false,
}));
},
[accessToken, clientId, idToken, removeStateAndLocalStorage, refreshToken],
);

/**
* This effect is responsible to set the authentication state based on the
* idToken stored in the local storage. It is used when the page is being
Expand All @@ -98,30 +115,10 @@ export const AuthProvider = ({
logoutReason: "",
});
} else {
removeStateAndLocalStorage(EXPIRED_SESSION);
await logoutUser({
idToken,
accessToken,
refreshToken,
clientId,
});
setAuthState((prev) => ({
...prev,
isLoading: false,
}));
await invalidateAndLogout(EXPIRED_SESSION);
}
} catch (_error) {
removeStateAndLocalStorage(EXPIRED_SESSION);
await logoutUser({
idToken,
accessToken,
refreshToken,
clientId,
});
setAuthState((prev) => ({
...prev,
isLoading: false,
}));
await invalidateAndLogout(EXPIRED_SESSION);
}
})();
} else {
Expand All @@ -133,14 +130,7 @@ export const AuthProvider = ({
return () => {
effectDidRunRef.current = true;
};
}, [
authState,
accessToken,
idToken,
refreshToken,
clientId,
removeStateAndLocalStorage,
]);
}, [authState.isLoading, idToken, invalidateAndLogout]);

const login: LoginType = async (username, password, type) => {
const _nonce = uuidv4();
Expand Down Expand Up @@ -219,18 +209,7 @@ export const AuthProvider = ({

const logout = async (e: any) => {
e?.preventDefault();

removeStateAndLocalStorage(LOGOUT_SESSION);
await logoutUser({
idToken,
accessToken,
refreshToken,
clientId,
});
setAuthState((prev) => ({
...prev,
isLoading: false,
}));
await invalidateAndLogout(LOGOUT_SESSION);
};

const getAccessToken = async () => {
Expand Down Expand Up @@ -260,13 +239,13 @@ export const AuthProvider = ({
/**
* refreshToken is not valid, so we need to re-authenticate the user.
*/
removeStateAndLocalStorage(ACCESS_TOKEN_ERROR);
await invalidateAndLogout(ACCESS_TOKEN_ERROR);
return "";
}
removeStateAndLocalStorage(ACCESS_TOKEN_ERROR);
await invalidateAndLogout(ACCESS_TOKEN_ERROR);
return "";
} catch (_error) {
removeStateAndLocalStorage(ACCESS_TOKEN_ERROR);
await invalidateAndLogout(ACCESS_TOKEN_ERROR);
return "";
}
};
Expand Down

0 comments on commit d02c421

Please sign in to comment.