Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add an async getUser function to Auth0ContextInterface #816

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions __tests__/auth-provider.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -953,6 +953,30 @@ describe('Auth0Provider', () => {
});
});

it('should return the user on getUser', async () => {
const userObject = { name: 'foo' };
clientMock.getUser.mockResolvedValue(userObject);
const wrapper = createWrapper();
const { result } = renderHook(() => useContext(Auth0Context), { wrapper });
let user;
await act(async () => {
user = await result.current.getUser();
});
expect(user).toBe(userObject);
});

it('should handle getUser errors', async () => {
const wrapper = createWrapper();
const { result } = renderHook(() => useContext(Auth0Context), { wrapper });

clientMock.getUser.mockRejectedValue(new Error('__test_error__'));
await act(async () => {
await expect(() => result.current.getUser()).rejects.toThrowError(
'__test_error__'
);
});
});

it('should allow passing a custom context', async () => {
const context = React.createContext<Auth0ContextInterface>(initialContext);
clientMock.getIdTokenClaims.mockResolvedValue({
Expand Down
9 changes: 9 additions & 0 deletions src/auth0-context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,14 @@ export interface Auth0ContextInterface<TUser extends User = User>
* @param url The URL to that should be used to retrieve the `state` and `code` values. Defaults to `window.location.href` if not given.
*/
handleRedirectCallback: (url?: string) => Promise<RedirectLoginResult>;

/**
* Returns the user information if available (decoded
* from the `id_token`).
*
* @typeparam TUser The type to return, has to extend {@link User}.
*/
getUser: <TUser extends User>() => Promise<TUser | undefined>;
}

/**
Expand All @@ -163,6 +171,7 @@ export const initialContext = {
loginWithPopup: stub,
logout: stub,
handleRedirectCallback: stub,
getUser: stub,
};

/**
Expand Down
15 changes: 15 additions & 0 deletions src/auth0-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
hasAuthParams,
loginError,
tokenError,
userError,
deprecateRedirectUri,
} from './utils';
import { reducer } from './reducer';
Expand Down Expand Up @@ -267,6 +268,18 @@ const Auth0Provider = (opts: Auth0ProviderOptions): JSX.Element => {
[client]
);

const getUser = useCallback(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async <TUser extends User>(): Promise<any> => {
try {
return await client.getUser<TUser>();
} catch (error) {
throw userError(error);
}
},
[client]
);

const contextValue = useMemo<Auth0ContextInterface<User>>(() => {
return {
...state,
Expand All @@ -277,6 +290,7 @@ const Auth0Provider = (opts: Auth0ProviderOptions): JSX.Element => {
loginWithPopup,
logout,
handleRedirectCallback,
getUser,
};
}, [
state,
Expand All @@ -287,6 +301,7 @@ const Auth0Provider = (opts: Auth0ProviderOptions): JSX.Element => {
loginWithPopup,
logout,
handleRedirectCallback,
getUser,
]);

return <context.Provider value={contextValue}>{children}</context.Provider>;
Expand Down
2 changes: 2 additions & 0 deletions src/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ export const loginError = normalizeErrorFn('Login failed');

export const tokenError = normalizeErrorFn('Get access token failed');

export const userError = normalizeErrorFn('Get user failed');

/**
* @ignore
* Helper function to map the v1 `redirectUri` option to the v2 `authorizationParams.redirect_uri`
Expand Down