Skip to content

Commit

Permalink
fix: handle both null user and user.expired when autoSignIn is disabl…
Browse files Browse the repository at this point in the history
…ed (#977)

* Handle user.expired when autoSignIn = false

Fixes #976

* Lint
  • Loading branch information
jamesdh authored Mar 16, 2023
1 parent 35626db commit 1a95930
Showing 1 changed file with 25 additions and 22 deletions.
47 changes: 25 additions & 22 deletions src/AuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -116,25 +116,29 @@ export const AuthProvider: FC<PropsWithChildren<AuthProviderProps>> = ({
await userManager.signinPopupCallback();
}, [userManager, onSignIn]);

/**
* Handles user auth flow on initial render.
*/
useEffect(() => {
isMountedRef.current = true;
(async () => {
const user = await userManager!.getUser();
/**
* Check if the user is returning back from OIDC.
*/
if (!user && hasCodeInUrl(location)) {
const user = (await userManager.signinCallback()) || null;
setUserData(user);
setIsLoading(false);
onSignIn && onSignIn(user);
return;
if (!user || user.expired) {
// If the user is returning back from the OIDC provider, get and set the user data.
if (hasCodeInUrl(location)) {
const user = (await userManager.signinCallback()) || null;
setUserData(user);
setIsLoading(false);
onSignIn && onSignIn(user);
}
// If autoSignIn is enabled, redirect to the OIDC provider.
else if (autoSignIn) {
const state = onBeforeSignIn ? onBeforeSignIn() : undefined;
await userManager.signinRedirect({ ...autoSignInArgs, state });
}
}

if ((!user || user.expired) && autoSignIn) {
const state = onBeforeSignIn ? onBeforeSignIn() : undefined;
await userManager.signinRedirect({ ...autoSignInArgs, state });
} else if (isMountedRef.current) {
// Otherwise if the user is already signed in, set the user data.
else if (isMountedRef.current) {
setUserData(user);
setIsLoading(false);
}
Expand All @@ -151,14 +155,13 @@ export const AuthProvider: FC<PropsWithChildren<AuthProviderProps>> = ({
const updateUserData: UserLoadedCallback = (user: User): void => {
setUserData(user);
};
const onSilentRenewError: SilentRenewErrorCallback = async (
error: Error,
): Promise<void> => {
if (autoSignOut) {
await signOutHooks();
await userManager.signoutRedirect(autoSignOutArgs);
}
};
const onSilentRenewError: SilentRenewErrorCallback =
async (): Promise<void> => {
if (autoSignOut) {
await signOutHooks();
await userManager.signoutRedirect(autoSignOutArgs);
}
};
userManager.events.addUserLoaded(updateUserData);
userManager.events.addSilentRenewError(onSilentRenewError);
return () => {
Expand Down

0 comments on commit 1a95930

Please sign in to comment.