-
Notifications
You must be signed in to change notification settings - Fork 5
feat(react): create use user mfa service hook and types #270
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
NaveenChand755
wants to merge
7
commits into
main
Choose a base branch
from
feat/mfa-service-hook
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+225
−0
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
da41875
feat(react): create use user service hook and types
NaveenChand755 6ef5ef0
fix(react): update service hook
NaveenChand755 38bca81
fix(react): update test cases
NaveenChand755 1f3768b
fix(react): update type for verify method
NaveenChand755 77be81b
fix(react): rename confirm mutation to verify
NaveenChand755 9579cca
fix(react): create shared service folder
NaveenChand755 8808f44
fix(react): test case update
NaveenChand755 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
109 changes: 109 additions & 0 deletions
109
packages/react/src/hooks/my-account/__tests__/use-user-mfa-service.test.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| import { mfaQueryKeys } from '@auth0/universal-components-core'; | ||
| import { renderHook, waitFor } from '@testing-library/react'; | ||
| import { describe, it, expect, vi, beforeEach } from 'vitest'; | ||
|
|
||
| import { useUserMFAService } from '@/hooks/my-account/shared/services/use-user-mfa-service'; | ||
| import * as useCoreClientModule from '@/hooks/shared/use-core-client'; | ||
| import { mockCore, setupMockUseCoreClient, createQueryClientWrapper } from '@/tests/utils'; | ||
|
|
||
| const { initMockCoreClient } = mockCore(); | ||
| let mockCoreClient: ReturnType<typeof initMockCoreClient>; | ||
|
|
||
| describe('useUserMFAService', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| mockCoreClient = initMockCoreClient(); | ||
| setupMockUseCoreClient(mockCoreClient, useCoreClientModule); | ||
| }); | ||
|
|
||
| const renderService = (onlyActive = false) => { | ||
| const { wrapper } = createQueryClientWrapper(); | ||
| return renderHook(() => useUserMFAService(onlyActive), { wrapper }); | ||
| }; | ||
|
|
||
| it('returns loading state initially', () => { | ||
| const { result } = renderService(); | ||
| expect(result.current.factorsQuery.isLoading).toBe(true); | ||
| }); | ||
|
|
||
| it('fetches and maps factors on success', async () => { | ||
| const { result } = renderService(); | ||
| await waitFor(() => expect(result.current.factorsQuery.isSuccess).toBe(true)); | ||
| expect(result.current.factorsQuery.data).toBeDefined(); | ||
| const apiClient = mockCoreClient.getMyAccountApiClient(); | ||
| expect(apiClient.factors.list).toHaveBeenCalledTimes(1); | ||
| expect(apiClient.authenticationMethods.list).toHaveBeenCalledTimes(1); | ||
| }); | ||
|
|
||
| it('does not fetch when coreClient is null', () => { | ||
| vi.spyOn(useCoreClientModule, 'useCoreClient').mockReturnValue({ coreClient: null }); | ||
|
|
||
| const { wrapper } = createQueryClientWrapper(); | ||
| const { result } = renderHook(() => useUserMFAService(false), { wrapper }); | ||
|
|
||
| expect(result.current.factorsQuery.fetchStatus).toBe('idle'); | ||
| }); | ||
|
|
||
| it('calls authenticationMethods.create with mapped params on enroll', async () => { | ||
| const apiClient = mockCoreClient.getMyAccountApiClient(); | ||
| vi.mocked(apiClient.authenticationMethods.create).mockResolvedValue({ | ||
| id: 'new_id', | ||
| auth_session: 'sess', | ||
| } as never); | ||
|
|
||
| const { result } = renderService(); | ||
| await waitFor(() => expect(result.current.factorsQuery.isSuccess).toBe(true)); | ||
|
|
||
| await result.current.enrollMutation.mutateAsync({ factorType: 'totp', options: {} }); | ||
|
|
||
| expect(apiClient.authenticationMethods.create).toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('calls authenticationMethods.delete and invalidates query on success', async () => { | ||
| const apiClient = mockCoreClient.getMyAccountApiClient(); | ||
|
|
||
| const { result } = renderService(); | ||
| await waitFor(() => expect(result.current.factorsQuery.isSuccess).toBe(true)); | ||
|
|
||
| const initialCallCount = vi.mocked(apiClient.factors.list).mock.calls.length; | ||
| await result.current.deleteMutation.mutateAsync('auth-id-123'); | ||
|
|
||
| expect(apiClient.authenticationMethods.delete).toHaveBeenCalledWith('auth-id-123'); | ||
| await waitFor(() => { | ||
| expect(vi.mocked(apiClient.factors.list).mock.calls.length).toBeGreaterThan(initialCallCount); | ||
| }); | ||
| }); | ||
|
|
||
| it('calls authenticationMethods.verify with correct params on confirm', async () => { | ||
| const apiClient = mockCoreClient.getMyAccountApiClient(); | ||
|
|
||
| const { result } = renderService(); | ||
| await waitFor(() => expect(result.current.factorsQuery.isSuccess).toBe(true)); | ||
|
|
||
| await result.current.verifyMutation.mutateAsync({ | ||
| factorType: 'totp', | ||
| authSession: 'sess-abc', | ||
| authenticationMethodId: 'method-123', | ||
| options: { userOtpCode: '123456' }, | ||
| }); | ||
|
|
||
| expect(apiClient.authenticationMethods.verify).toHaveBeenCalledWith( | ||
| 'method-123', | ||
| expect.anything(), | ||
| ); | ||
| }); | ||
|
|
||
| it('registers query under the onlyActive=true key when onlyActive is true', async () => { | ||
| const { wrapper, queryClient } = createQueryClientWrapper(); | ||
| const { result } = renderHook(() => useUserMFAService(true), { wrapper }); | ||
|
|
||
| await waitFor(() => expect(result.current.factorsQuery.isSuccess).toBe(true)); | ||
|
|
||
| const cachedKeys = queryClient | ||
| .getQueryCache() | ||
| .getAll() | ||
| .map((q) => q.queryKey); | ||
| expect(cachedKeys).toContainEqual(mfaQueryKeys.factors(true)); | ||
| expect(cachedKeys).not.toContainEqual(mfaQueryKeys.factors(false)); | ||
| }); | ||
| }); |
93 changes: 93 additions & 0 deletions
93
packages/react/src/hooks/my-account/shared/services/use-user-mfa-service.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| /** | ||
| * MFA service hook with TanStack Query. | ||
| * @module use-user-mfa-service | ||
| * @internal | ||
| */ | ||
|
|
||
| import { | ||
| MFAMappers, | ||
| mfaQueryKeys, | ||
| type Authenticator, | ||
| type MFAType, | ||
| type EnrollOptions, | ||
| type ConfirmEnrollmentOptions, | ||
| } from '@auth0/universal-components-core'; | ||
| import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; | ||
|
|
||
| import { useCoreClient } from '@/hooks/shared/use-core-client'; | ||
| import type { UseUserMFAServiceReturn } from '@/types/my-account/mfa/mfa-types'; | ||
|
|
||
| /** | ||
| * Internal service hook for MFA operations backed by TanStack Query. | ||
| * Provides queries and mutations; use `useUserMFA` for the public API. | ||
| * @param onlyActive - Whether to return only active factors. | ||
| * @returns MFA query and mutation handlers for factor listing and enrollment lifecycle operations. | ||
| * @internal | ||
| */ | ||
| export function useUserMFAService(onlyActive: boolean): UseUserMFAServiceReturn { | ||
| const { coreClient } = useCoreClient(); | ||
| const queryClient = useQueryClient(); | ||
|
|
||
| const factorsQuery = useQuery<Record<MFAType, Authenticator[]>>({ | ||
| queryKey: mfaQueryKeys.factors(onlyActive), | ||
| queryFn: async () => { | ||
| const client = coreClient!.getMyAccountApiClient(); | ||
| const [availableFactors, enrolledFactors] = await Promise.all([ | ||
| client.factors.list(), | ||
| client.authenticationMethods.list(), | ||
| ]); | ||
| return MFAMappers.fromAPI(availableFactors, enrolledFactors, onlyActive) as Record< | ||
| MFAType, | ||
| Authenticator[] | ||
| >; | ||
| }, | ||
| enabled: !!coreClient, | ||
| }); | ||
|
|
||
| const enrollMutation = useMutation({ | ||
| mutationFn: ({ | ||
| factorType, | ||
| options = {}, | ||
| }: { | ||
| factorType: MFAType; | ||
| options?: EnrollOptions; | ||
| }) => { | ||
| const client = coreClient!.getMyAccountApiClient(); | ||
| const params = MFAMappers.buildEnrollParams(factorType, options); | ||
| return client.authenticationMethods.create(params); | ||
| }, | ||
| }); | ||
|
|
||
| const deleteMutation = useMutation({ | ||
| mutationFn: (authenticatorId: string) => | ||
| coreClient!.getMyAccountApiClient().authenticationMethods.delete(authenticatorId), | ||
| onSuccess: () => { | ||
| queryClient.invalidateQueries({ queryKey: mfaQueryKeys.factors(onlyActive) }); | ||
| }, | ||
| }); | ||
|
|
||
| const verifyMutation = useMutation({ | ||
| mutationFn: ({ | ||
| factorType, | ||
| authSession, | ||
| authenticationMethodId, | ||
| options, | ||
| }: { | ||
| factorType: MFAType; | ||
| authSession: string; | ||
| authenticationMethodId: string; | ||
| options: ConfirmEnrollmentOptions; | ||
| }) => { | ||
| const client = coreClient!.getMyAccountApiClient(); | ||
| const params = MFAMappers.buildConfirmEnrollmentParams(factorType, authSession, options); | ||
| return client.authenticationMethods.verify(authenticationMethodId, params); | ||
| }, | ||
| }); | ||
|
|
||
| return { | ||
| factorsQuery, | ||
| enrollMutation, | ||
| deleteMutation, | ||
| verifyMutation, | ||
| }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.