Skip to content

feat(hook): add new create user hook #1152

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

Open
wants to merge 3 commits into
base: master
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
57 changes: 57 additions & 0 deletions src/hooks/__tests__/use-auth0.spec.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ const mockAuth0 = {
passwordRealm: jest.fn().mockResolvedValue(mockCredentials),
exchangeNativeSocial: jest.fn().mockResolvedValue(mockCredentials),
revoke: jest.fn().mockResolvedValue(mockCredentials),
createUser: jest.fn(),
},
credentialsManager: {
getCredentials: jest.fn().mockResolvedValue(mockCredentials),
Expand Down Expand Up @@ -114,6 +115,11 @@ describe('The useAuth0 hook', () => {
expect(result.current.cancelWebAuth()).toBeDefined();
});

it('defines createUser', () => {
const { result } = renderHook(() => useAuth0());
expect(result.current.createUser).toBeDefined();
});

it('isLoading is true until initialization finishes', async () => {
const { result } = renderHook(() => useAuth0(), {
wrapper,
Expand Down Expand Up @@ -1215,6 +1221,57 @@ describe('The useAuth0 hook', () => {
mockAuth0.credentialsManager.hasValidCredentials
).toHaveBeenCalledWith(100);
});

it('throws an error when createUser is called without a wrapper', () => {
const { result } = renderHook(() => useAuth0());
expect(() =>
result.current.createUser({
email: '[email protected]',
password: 'pass',
connection: 'Username-Password-Authentication',
})
).toThrowError(/no provider was set/i);
});

it('can create a user', async () => {
const mockUser = { email: '[email protected]', user_id: 'user123' };
mockAuth0.auth.createUser = jest.fn().mockResolvedValue(mockUser);
const { result } = renderHook(() => useAuth0(), { wrapper });
let user;
await act(async () => {
user = await result.current.createUser({
email: '[email protected]',
password: 'pass',
connection: 'Username-Password-Authentication',
});
});
expect(mockAuth0.auth.createUser).toHaveBeenCalledWith({
email: '[email protected]',
password: 'pass',
connection: 'Username-Password-Authentication',
});
expect(user).toEqual(mockUser);
});

it('sets the error property when an error is raised in createUser', async () => {
const errorToThrow = new Error('Create user error');
mockAuth0.auth.createUser = jest.fn().mockRejectedValue(errorToThrow);
const { result } = renderHook(() => useAuth0(), { wrapper });
let thrown;
await act(async () => {
try {
await result.current.createUser({
email: '[email protected]',
password: 'pass',
connection: 'Username-Password-Authentication',
});
} catch (e) {
thrown = e;
}
});
expect(result.current.error).toBe(errorToThrow);
expect(thrown).toBe(errorToThrow);
});
});

describe('The Auth0Provider component', () => {
Expand Down
7 changes: 7 additions & 0 deletions src/hooks/auth0-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import type {
ExchangeNativeSocialOptions,
RevokeOptions,
ResetPasswordOptions,
CreateUserOptions,
} from '../types';
import BaseError from '../utils/baseError';

Expand Down Expand Up @@ -138,6 +139,11 @@ export interface Auth0ContextInterface<TUser extends User = User>
*Request an email with instructions to change password of a user {@link Auth#resetPassword}
*/
resetPassword: (parameters: ResetPasswordOptions) => Promise<void>;

/**
*Creates a new user with the given email and password {@link Auth#createUser}
*/
createUser: (parameters: CreateUserOptions) => Promise<Partial<User>>;
}

export interface AuthState<TUser extends User = User> {
Expand Down Expand Up @@ -181,6 +187,7 @@ const initialContext = {
authorizeWithExchangeNativeSocial: stub,
revokeRefreshToken: stub,
resetPassword: stub,
createUser: stub,
};

const Auth0Context = createContext<Auth0ContextInterface>(initialContext);
Expand Down
16 changes: 16 additions & 0 deletions src/hooks/auth0-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import type {
ExchangeNativeSocialOptions,
RevokeOptions,
ResetPasswordOptions,
CreateUserOptions,
} from '../types';
import type { CustomJwtPayload } from '../internal-types';
import { convertUser } from '../utils/userConversion';
Expand Down Expand Up @@ -386,6 +387,19 @@ const Auth0Provider = ({
}
}, [client]);

const createUser = useCallback(
async (parameters: CreateUserOptions) => {
try {
const user = await client.auth.createUser(parameters);
return user;
} catch (error) {
dispatch({ type: 'ERROR', error: error as BaseError });
throw error;
}
},
[client]
);

const contextValue = useMemo(
() => ({
...state,
Expand All @@ -407,6 +421,7 @@ const Auth0Provider = ({
authorizeWithExchangeNativeSocial,
revokeRefreshToken,
resetPassword,
createUser,
}),
[
state,
Expand All @@ -428,6 +443,7 @@ const Auth0Provider = ({
authorizeWithExchangeNativeSocial,
revokeRefreshToken,
resetPassword,
createUser,
]
);

Expand Down
1 change: 1 addition & 0 deletions src/hooks/use-auth0.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import type { Auth0ContextInterface } from './auth0-context';
* authorizeWithPasswordRealm,
* authorizeWithExchangeNativeSocial,
* revokeRefreshToken
* createUser
* } = useAuth0();
* ```
*
Expand Down