Skip to content

Commit

Permalink
fix: avoid reinitiating partial authentication flow when user is alre…
Browse files Browse the repository at this point in the history
…ady authenticated (#962)

* fix: only allow performing signinCallback if no user exists

See authts/oidc-client-ts#402

* refactor: add type info and avoid async getUser() request since the callback function is already provided the user

* chore: prettier
  • Loading branch information
jamesdh authored Mar 8, 2023
1 parent 3eaf620 commit 7c88d80
Showing 1 changed file with 7 additions and 8 deletions.
15 changes: 7 additions & 8 deletions src/AuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
User,
SigninRedirectArgs,
SignoutRedirectArgs,
UserLoadedCallback,
} from 'oidc-client-ts';
import {
Location,
Expand Down Expand Up @@ -123,19 +124,18 @@ export const AuthProvider: FC<PropsWithChildren<AuthProviderProps>> = ({
(async () => {
// Store current isMounted since this could change while awaiting async operations below
const isMounted = isMountedRef.current;

const user = await userManager!.getUser();
/**
* Check if the user is returning back from OIDC.
*/
if (hasCodeInUrl(location)) {
if (!user && hasCodeInUrl(location)) {
const user = (await userManager.signinCallback()) || null;
setUserData(user);
setIsLoading(false);
onSignIn && onSignIn(user);
return;
}

const user = await userManager!.getUser();
if ((!user || user.expired) && autoSignIn) {
const state = onBeforeSignIn ? onBeforeSignIn() : undefined;
userManager.signinRedirect({ state });
Expand All @@ -146,15 +146,14 @@ export const AuthProvider: FC<PropsWithChildren<AuthProviderProps>> = ({
})();
}, [location, userManager, autoSignIn, onBeforeSignIn, onSignIn]);

/**
* Registers a UserLoadedCallback to update the userData state on a userLoaded event
*/
useEffect(() => {
// for refreshing react state when new state is available in e.g. session storage
const updateUserData = async () => {
const user = await userManager.getUser();
const updateUserData: UserLoadedCallback = (user: User): void => {
isMountedRef.current && setUserData(user);
};

userManager.events.addUserLoaded(updateUserData);

return () => userManager.events.removeUserLoaded(updateUserData);
}, [userManager]);

Expand Down

0 comments on commit 7c88d80

Please sign in to comment.