-
Notifications
You must be signed in to change notification settings - Fork 451
Expand file tree
/
Copy pathuseOAuthConsent.tsx
More file actions
65 lines (55 loc) · 2.38 KB
/
useOAuthConsent.tsx
File metadata and controls
65 lines (55 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { eventMethodCalled } from '../../telemetry/events/method-called';
import type { LoadedClerk } from '../../types/clerk';
import { useAssertWrappedByClerkProvider, useClerkInstanceContext } from '../contexts';
import { defineKeepPreviousDataFn } from '../query/keep-previous-data';
import { useClerkQuery } from '../query/useQuery';
import { useUserBase } from './base/useUserBase';
import { 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).
*
* @example
* ```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, keepPreviousData = true, enabled = true } = params;
const clerk = useClerkInstanceContext();
const user = useUserBase();
const oauthClientId = (oauthClientIdParam ?? '').trim();
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 });
}