Skip to content

Commit

Permalink
feat: add onSignInError to AuthProvider (#1030)
Browse files Browse the repository at this point in the history
This new error callback let us have a better control (for giving feedback to the users) when the `signIn` function fails

fixes #929

Co-authored-by: berna <[email protected]>
  • Loading branch information
simenandre and bbernag authored Nov 11, 2023
1 parent 32458f0 commit 964876f
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
22 changes: 18 additions & 4 deletions src/AuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ export const AuthProvider: FC<PropsWithChildren<AuthProviderProps>> = ({
onSignIn,
onSignOut,
location = window.location,
onSignInError,
...props
}) => {
const [isLoading, setIsLoading] = useState(true);
Expand Down Expand Up @@ -132,9 +133,15 @@ export const AuthProvider: FC<PropsWithChildren<AuthProviderProps>> = ({
if (isMounted && (!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);
onSignIn && onSignIn(user);
const user = await userManager.signinCallback().catch((error) => {
if (onSignInError) {
onSignInError(error);
}
});
if (user) {
setUserData(user);
onSignIn && onSignIn(user);
}
}
// If autoSignIn is enabled, redirect to the OIDC provider.
else if (autoSignIn) {
Expand All @@ -152,7 +159,14 @@ export const AuthProvider: FC<PropsWithChildren<AuthProviderProps>> = ({
isMounted = false;
isMountedRef.current = false;
};
}, [location, userManager, autoSignIn, onBeforeSignIn, onSignIn]);
}, [
location,
userManager,
autoSignIn,
onBeforeSignIn,
onSignIn,
onSignInError,
]);

/**
* Registers UserManager event callbacks for handling changes to user state due to automaticSilentRenew, session expiry, etc.
Expand Down
5 changes: 5 additions & 0 deletions src/AuthContextInterface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,11 @@ export interface AuthProviderProps {
* On sign out hook. Can be a async function.
*/
onSignOut?: (options?: AuthProviderSignOutProps) => Promise<void> | void;

/**
* On sign in error. Can be a async function.
*/
onSignInError?: (error: Error) => void;
}

export interface AuthContextProps {
Expand Down

0 comments on commit 964876f

Please sign in to comment.