-
Notifications
You must be signed in to change notification settings - Fork 444
feat(shared,nextjs,react): Introduce useOAuthConsent hook
#8286
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
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
7aaf6ed
feat(react): add `useOAuthConsent` hook
jfoshee 7444213
read `scope` and `client_id` from location search params
jfoshee 439b3b8
Merge branch 'main' into jfoshee/add-hook-use-oauth-consent
wobsoriano 7bf0994
chore: Clean up hook
wobsoriano 26604b8
Merge branch 'main' into jfoshee/add-hook-use-oauth-consent
wobsoriano 844917f
refactor(shared): clean up useOAuthConsent hook
wobsoriano 9e8a4fe
chore: fix jsdoc imports
wobsoriano 71ad9f6
Merge branch 'main' into jfoshee/add-hook-use-oauth-consent
wobsoriano 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| --- | ||
| '@clerk/shared': minor | ||
| '@clerk/react': minor | ||
| '@clerk/nextjs': minor | ||
| --- | ||
|
|
||
| Introduce internal `useOAuthConsent()` hook for fetching OAuth consent screen metadata for the signed-in user. |
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
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
31 changes: 31 additions & 0 deletions
31
packages/shared/src/react/hooks/__tests__/useOAuthConsent.shared.spec.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,31 @@ | ||
| import { describe, expect, it } from 'vitest'; | ||
|
|
||
| import { readOAuthConsentFromSearch } from '../useOAuthConsent.shared'; | ||
|
|
||
| describe('readOAuthConsentFromSearch', () => { | ||
| it('parses client_id and scope from a location.search-style string', () => { | ||
| expect(readOAuthConsentFromSearch('?client_id=myapp&scope=openid%20email')).toEqual({ | ||
| oauthClientId: 'myapp', | ||
| scope: 'openid email', | ||
| }); | ||
| }); | ||
|
|
||
| it('parses without a leading question mark', () => { | ||
| expect(readOAuthConsentFromSearch('client_id=x&scope=y')).toEqual({ | ||
| oauthClientId: 'x', | ||
| scope: 'y', | ||
| }); | ||
| }); | ||
|
|
||
| it('returns empty client id and undefined scope when search is empty', () => { | ||
| expect(readOAuthConsentFromSearch('')).toEqual({ | ||
| oauthClientId: '', | ||
| }); | ||
| }); | ||
|
|
||
| it('omits scope in the result when scope is absent', () => { | ||
| expect(readOAuthConsentFromSearch('?client_id=only')).toEqual({ | ||
| oauthClientId: 'only', | ||
| }); | ||
| }); | ||
| }); |
148 changes: 148 additions & 0 deletions
148
packages/shared/src/react/hooks/__tests__/useOAuthConsent.spec.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,148 @@ | ||
| import { renderHook, waitFor } from '@testing-library/react'; | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest'; | ||
|
|
||
| import { useOAuthConsent } from '../useOAuthConsent'; | ||
| import { createMockClerk, createMockQueryClient, createMockUser } from './mocks/clerk'; | ||
| import { wrapper } from './wrapper'; | ||
|
|
||
| const consentInfo = { | ||
| oauthApplicationName: 'My App', | ||
| oauthApplicationLogoUrl: 'https://img.example/logo.png', | ||
| oauthApplicationUrl: 'https://app.example', | ||
| clientId: 'client_abc', | ||
| state: 's', | ||
| scopes: [] as { scope: string; description: string | null; requiresConsent: boolean }[], | ||
| }; | ||
|
|
||
| const getConsentInfoSpy = vi.fn(() => Promise.resolve(consentInfo)); | ||
|
|
||
| const defaultQueryClient = createMockQueryClient(); | ||
|
|
||
| const mockClerk = createMockClerk({ | ||
| oauthApplication: { | ||
| getConsentInfo: getConsentInfoSpy, | ||
| }, | ||
| queryClient: defaultQueryClient, | ||
| }); | ||
|
|
||
| const userState: { current: { id: string } | null } = { | ||
| current: createMockUser(), | ||
| }; | ||
|
|
||
| vi.mock('../../contexts', () => { | ||
| return { | ||
| useAssertWrappedByClerkProvider: () => {}, | ||
| useClerkInstanceContext: () => mockClerk, | ||
| useInitialStateContext: () => undefined, | ||
| }; | ||
| }); | ||
|
|
||
| vi.mock('../base/useUserBase', () => ({ | ||
| useUserBase: () => userState.current, | ||
| })); | ||
|
|
||
| describe('useOAuthConsent', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| defaultQueryClient.client.clear(); | ||
| mockClerk.loaded = true; | ||
| userState.current = createMockUser(); | ||
| mockClerk.oauthApplication = { | ||
| getConsentInfo: getConsentInfoSpy, | ||
| }; | ||
| window.history.replaceState({}, '', '/'); | ||
| }); | ||
|
|
||
| it('fetches consent metadata when signed in', async () => { | ||
| const { result } = renderHook(() => useOAuthConsent({ oauthClientId: 'my_client' }), { wrapper }); | ||
|
|
||
| await waitFor(() => expect(result.current.isLoading).toBe(false)); | ||
|
|
||
| expect(getConsentInfoSpy).toHaveBeenCalledTimes(1); | ||
| expect(getConsentInfoSpy).toHaveBeenCalledWith({ oauthClientId: 'my_client' }); | ||
| expect(result.current.data).toEqual(consentInfo); | ||
| expect(result.current.error).toBeNull(); | ||
| }); | ||
|
|
||
| it('passes scope to getConsentInfo when provided', async () => { | ||
| const { result } = renderHook(() => useOAuthConsent({ oauthClientId: 'cid', scope: 'openid email' }), { wrapper }); | ||
|
|
||
| await waitFor(() => expect(result.current.isLoading).toBe(false)); | ||
|
|
||
| expect(getConsentInfoSpy).toHaveBeenCalledWith({ oauthClientId: 'cid', scope: 'openid email' }); | ||
| expect(result.current.data).toEqual(consentInfo); | ||
| }); | ||
|
|
||
| it('does not call getConsentInfo when user is null', () => { | ||
| userState.current = null; | ||
|
|
||
| const { result } = renderHook(() => useOAuthConsent({ oauthClientId: 'cid' }), { wrapper }); | ||
|
|
||
| expect(getConsentInfoSpy).not.toHaveBeenCalled(); | ||
| expect(result.current.isLoading).toBe(false); | ||
| }); | ||
|
|
||
| it('does not call getConsentInfo when clerk.loaded is false', () => { | ||
| mockClerk.loaded = false; | ||
|
|
||
| const { result } = renderHook(() => useOAuthConsent({ oauthClientId: 'cid' }), { wrapper }); | ||
|
|
||
| expect(getConsentInfoSpy).not.toHaveBeenCalled(); | ||
| expect(result.current.isLoading).toBe(false); | ||
| }); | ||
|
|
||
| it('does not call getConsentInfo when enabled is false', () => { | ||
| const { result } = renderHook(() => useOAuthConsent({ oauthClientId: 'cid', enabled: false }), { wrapper }); | ||
|
|
||
| expect(getConsentInfoSpy).not.toHaveBeenCalled(); | ||
| expect(result.current.isLoading).toBe(false); | ||
| }); | ||
|
|
||
| it('does not call getConsentInfo when oauthClientId is empty', () => { | ||
| const { result } = renderHook(() => useOAuthConsent({ oauthClientId: '' }), { wrapper }); | ||
|
|
||
| expect(getConsentInfoSpy).not.toHaveBeenCalled(); | ||
| expect(result.current.isLoading).toBe(false); | ||
| }); | ||
|
|
||
| it('uses client_id and scope from the URL when hook params omit them', async () => { | ||
| window.history.replaceState({}, '', '/?client_id=from_url&scope=openid%20email'); | ||
|
|
||
| const { result } = renderHook(() => useOAuthConsent(), { wrapper }); | ||
|
|
||
| await waitFor(() => expect(result.current.isLoading).toBe(false)); | ||
|
|
||
| expect(getConsentInfoSpy).toHaveBeenCalledTimes(1); | ||
| expect(getConsentInfoSpy).toHaveBeenCalledWith({ oauthClientId: 'from_url', scope: 'openid email' }); | ||
| expect(result.current.data).toEqual(consentInfo); | ||
| }); | ||
|
|
||
| it('prefers explicit oauthClientId over URL client_id', async () => { | ||
| window.history.replaceState({}, '', '/?client_id=from_url'); | ||
|
|
||
| const { result } = renderHook(() => useOAuthConsent({ oauthClientId: 'explicit_id' }), { wrapper }); | ||
|
|
||
| await waitFor(() => expect(result.current.isLoading).toBe(false)); | ||
|
|
||
| expect(getConsentInfoSpy).toHaveBeenCalledWith({ oauthClientId: 'explicit_id' }); | ||
| }); | ||
|
|
||
| it('does not fall back to URL client_id when oauthClientId is explicitly empty', () => { | ||
| window.history.replaceState({}, '', '/?client_id=from_url'); | ||
|
|
||
| const { result } = renderHook(() => useOAuthConsent({ oauthClientId: '' }), { wrapper }); | ||
|
|
||
| expect(getConsentInfoSpy).not.toHaveBeenCalled(); | ||
| expect(result.current.isLoading).toBe(false); | ||
| }); | ||
|
|
||
| it('prefers explicit scope over URL scope', async () => { | ||
| window.history.replaceState({}, '', '/?client_id=cid&scope=from_url'); | ||
|
|
||
| const { result } = renderHook(() => useOAuthConsent({ scope: 'explicit_scope' }), { wrapper }); | ||
|
|
||
| await waitFor(() => expect(result.current.isLoading).toBe(false)); | ||
|
|
||
| expect(getConsentInfoSpy).toHaveBeenCalledWith({ oauthClientId: 'cid', scope: 'explicit_scope' }); | ||
| }); | ||
| }); |
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
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,43 @@ | ||
| import { useMemo } from 'react'; | ||
|
|
||
| import type { GetOAuthConsentInfoParams } from '../../types'; | ||
| import { STABLE_KEYS } from '../stable-keys'; | ||
| import { createCacheKeys } from './createCacheKeys'; | ||
|
|
||
| /** | ||
| * Parses OAuth authorize-style query data from a search string (typically `window.location.search`). | ||
| * | ||
| * @internal | ||
| */ | ||
| export function readOAuthConsentFromSearch(search: string): { | ||
| oauthClientId: string; | ||
| scope?: string; | ||
| } { | ||
| const sp = new URLSearchParams(search); | ||
| const oauthClientId = sp.get('client_id') ?? ''; | ||
| const scopeValue = sp.get('scope'); | ||
| if (scopeValue === null) { | ||
| return { oauthClientId }; | ||
| } | ||
| return { oauthClientId, scope: scopeValue }; | ||
| } | ||
|
|
||
| export function useOAuthConsentCacheKeys(params: { userId: string | null; oauthClientId: string; scope?: string }) { | ||
| const { userId, oauthClientId, scope } = params; | ||
| return useMemo(() => { | ||
| const args: Pick<GetOAuthConsentInfoParams, 'oauthClientId'> & { scope?: string } = { oauthClientId }; | ||
| if (scope !== undefined) { | ||
| args.scope = scope; | ||
| } | ||
| return createCacheKeys({ | ||
| stablePrefix: STABLE_KEYS.OAUTH_CONSENT_INFO_KEY, | ||
| authenticated: true, | ||
| tracked: { | ||
| userId: userId ?? null, | ||
| }, | ||
| untracked: { | ||
| args, | ||
| }, | ||
| }); | ||
| }, [userId, oauthClientId, scope]); | ||
| } |
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,96 @@ | ||
| 'use client'; | ||
|
|
||
| import { useMemo } from 'react'; | ||
|
|
||
| import { eventMethodCalled } from '../../telemetry/events/method-called'; | ||
| import type { LoadedClerk } from '../../types/clerk'; | ||
| import { defineKeepPreviousDataFn } from '../clerk-rq/keep-previous-data'; | ||
| import { useClerkQuery } from '../clerk-rq/useQuery'; | ||
| import { useAssertWrappedByClerkProvider, useClerkInstanceContext } from '../contexts'; | ||
| import { useUserBase } from './base/useUserBase'; | ||
| import { readOAuthConsentFromSearch, useOAuthConsentCacheKeys } from './useOAuthConsent.shared'; | ||
| import type { UseOAuthConsentParams, UseOAuthConsentReturn } from './useOAuthConsent.types'; | ||
|
|
||
| const HOOK_NAME = 'useOAuthConsent'; | ||
|
|
||
| /** | ||
| * The `useOAuthConsent()` hook loads OAuth application consent metadata for the **signed-in** user | ||
| * (`GET /me/oauth/consent/{oauthClientId}`). Ensure the user is authenticated before relying on this hook | ||
| * (for example, redirect to sign-in on your custom consent route). | ||
| * | ||
| * `oauthClientId` and `scope` are optional. On the client, values default from a single snapshot of | ||
| * `window.location.search` (`client_id` and `scope`). Pass them explicitly to override. | ||
| * | ||
| * @internal | ||
| * | ||
| * @example | ||
| * ### From the URL (`?client_id=...&scope=...`) | ||
| * | ||
| * ```tsx | ||
| * import { useOAuthConsent } from '@clerk/react/internal' | ||
| * | ||
| * export default function OAuthConsentPage() { | ||
| * const { data, isLoading, error } = useOAuthConsent() | ||
| * // ... | ||
| * } | ||
| * ``` | ||
| * | ||
| * @example | ||
| * ### Explicit values (override URL) | ||
| * | ||
| * ```tsx | ||
| * import { useOAuthConsent } from '@clerk/react/internal' | ||
| * | ||
| * const { data, isLoading, error } = useOAuthConsent({ | ||
| * oauthClientId: clientIdFromProps, | ||
| * scope: scopeFromProps, | ||
| * }) | ||
| * ``` | ||
| */ | ||
| export function useOAuthConsent(params: UseOAuthConsentParams = {}): UseOAuthConsentReturn { | ||
| useAssertWrappedByClerkProvider(HOOK_NAME); | ||
|
|
||
| const { oauthClientId: oauthClientIdParam, scope: scopeParam, keepPreviousData = true, enabled = true } = params; | ||
| const clerk = useClerkInstanceContext(); | ||
| const user = useUserBase(); | ||
|
|
||
| const fromUrl = useMemo(() => { | ||
| if (typeof window === 'undefined' || !window.location) { | ||
| return { oauthClientId: '' }; | ||
| } | ||
| return readOAuthConsentFromSearch(window.location.search); | ||
| }, []); | ||
|
|
||
| const oauthClientId = (oauthClientIdParam !== undefined ? oauthClientIdParam : fromUrl.oauthClientId).trim(); | ||
| const scope = scopeParam !== undefined ? scopeParam : fromUrl.scope; | ||
|
|
||
| clerk.telemetry?.record(eventMethodCalled(HOOK_NAME)); | ||
|
|
||
| const { queryKey } = useOAuthConsentCacheKeys({ | ||
| userId: user?.id ?? null, | ||
| oauthClientId, | ||
| scope, | ||
| }); | ||
|
|
||
| const hasClientId = oauthClientId.length > 0; | ||
| const queryEnabled = Boolean(user) && hasClientId && enabled && clerk.loaded; | ||
|
|
||
| const query = useClerkQuery({ | ||
| queryKey, | ||
| queryFn: () => fetchConsentInfo(clerk, { oauthClientId, scope }), | ||
| enabled: queryEnabled, | ||
| placeholderData: defineKeepPreviousDataFn(keepPreviousData && queryEnabled), | ||
| }); | ||
|
|
||
| return { | ||
| data: query.data, | ||
| error: (query.error ?? null) as UseOAuthConsentReturn['error'], | ||
| isLoading: query.isLoading, | ||
| isFetching: query.isFetching, | ||
| }; | ||
| } | ||
|
|
||
| function fetchConsentInfo(clerk: LoadedClerk, params: { oauthClientId: string; scope?: string }) { | ||
| const { oauthClientId, scope } = params; | ||
| return clerk.oauthApplication.getConsentInfo(scope !== undefined ? { oauthClientId, scope } : { oauthClientId }); | ||
| } | ||
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
let's change
datatoconsentInfoThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
After doing another review, I'd say we should keep
datahere. Every other useClerkQuery-based hook returnsdata, not a named field.The hook name already tells us what data is here, which is the consent info, and consumers can always destructure as
const { data: consentInfo } = useOAuthConsent() if they want a named variable.