Repository navigation
Expand file tree
/
Copy pathAPIKeys.tsx
More file actions
251 lines (226 loc) · 7.81 KB
/
Copy pathAPIKeys.tsx
File metadata and controls
251 lines (226 loc) · 7.81 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
import { isClerkAPIResponseError } from '@clerk/shared/error';
import { isOrganizationId } from '@clerk/shared/internal/clerk-js/organization';
import { __internal_useOrganizationBase, useAPIKeys, useClerk, useUser } from '@clerk/shared/react';
import type { APIKeyResource } from '@clerk/shared/types';
import { lazy, useState } from 'react';
import { useProtect } from '@/ui/common';
import { useAPIKeysContext, withCoreUserGuard } from '@/ui/contexts';
import { Box, Button, Col, descriptors, Flex, Flow, localizationKeys, useLocalizations } from '@/ui/customizables';
import { Action } from '@/ui/elements/Action';
import { useCardState, withCardStateProvider } from '@/ui/elements/contexts';
import { Pagination } from '@/ui/elements/Pagination';
import { SearchInput } from '@/ui/elements/SearchInput';
import { useDebounce } from '@/ui/hooks';
import { mqu } from '@/ui/styledSystem';
import { handleError } from '@/ui/utils/errorHandler';
import { APIKeysTable } from './ApiKeysTable';
import type { OnCreateParams } from './CreateAPIKeyForm';
import { CreateAPIKeyForm } from './CreateAPIKeyForm';
import { useAPIKeysPagination } from './utils';
type APIKeysPageProps = {
subject: string;
perPage?: number;
revokeModalRoot?: React.MutableRefObject<HTMLElement | null>;
};
const RevokeAPIKeyConfirmationModal = lazy(() =>
import(/* webpackChunkName: "revoke-api-key-modal"*/ './RevokeAPIKeyConfirmationModal').then(module => ({
default: module.RevokeAPIKeyConfirmationModal,
})),
);
const CopyAPIKeyModal = lazy(() =>
import(/* webpackChunkName: "copy-api-key-modal"*/ './CopyAPIKeyModal').then(module => ({
default: module.CopyAPIKeyModal,
})),
);
const apiKeysSearchDebounceMs = 500;
const API_KEYS_PAGE_SIZE = 10;
export const APIKeysPage = ({ subject, perPage, revokeModalRoot }: APIKeysPageProps) => {
const isOrg = isOrganizationId(subject);
const canReadAPIKeys = useProtect({ permission: 'org:sys_api_keys:read' });
const canManageAPIKeys = useProtect({ permission: 'org:sys_api_keys:manage' });
const [searchValue, setSearchValue] = useState('');
const debouncedSearchValue = useDebounce(searchValue, apiKeysSearchDebounceMs);
const query = debouncedSearchValue.trim();
const {
data: apiKeys,
isLoading,
isFetching,
page,
fetchPage,
pageCount,
count: itemCount,
revalidate: invalidateAll,
} = useAPIKeys({
subject,
pageSize: perPage ?? API_KEYS_PAGE_SIZE,
query,
keepPreviousData: true,
enabled: isOrg ? canReadAPIKeys : true,
});
useAPIKeysPagination({
query,
page,
pageCount,
isFetching,
fetchPage,
});
const startingRow = itemCount > 0 ? Math.max(0, (page - 1) * (perPage ?? API_KEYS_PAGE_SIZE)) + 1 : 0;
const endingRow = Math.min(page * (perPage ?? API_KEYS_PAGE_SIZE), itemCount);
const handlePageChange = (newPage: number) => {
fetchPage(newPage);
};
const card = useCardState();
const clerk = useClerk();
const [apiKey, setAPIKey] = useState<APIKeyResource | null>(null);
const { t } = useLocalizations();
const [isRevokeModalOpen, setIsRevokeModalOpen] = useState(false);
const [selectedAPIKeyID, setSelectedAPIKeyID] = useState('');
const [selectedAPIKeyName, setSelectedAPIKeyName] = useState('');
const [isCopyModalOpen, setIsCopyModalOpen] = useState(false);
const handleCreateAPIKey = async (params: OnCreateParams) => {
try {
card.setLoading();
const apiKey = await clerk.apiKeys.create({
...params,
subject,
});
void invalidateAll();
card.setError(undefined);
setIsCopyModalOpen(true);
setAPIKey(apiKey);
} catch (err: any) {
if (!isClerkAPIResponseError(err)) {
handleError(err, [], card.setError);
return;
}
switch (err.errors?.[0]?.code) {
case 'token_quota_exceeded':
card.setError(t(localizationKeys('unstable__errors.api_key_usage_exceeded')));
break;
case 'token_creation_conflict':
card.setError(t(localizationKeys('unstable__errors.api_key_name_already_exists')));
break;
default:
handleError(err, [], card.setError);
}
} finally {
card.setIdle();
}
};
const handleRevoke = (apiKeyID: string, apiKeyName: string) => {
setSelectedAPIKeyID(apiKeyID);
setSelectedAPIKeyName(apiKeyName);
setIsRevokeModalOpen(true);
};
return (
<Col
gap={4}
sx={{ width: '100%' }}
elementDescriptor={descriptors.apiKeys}
>
<Action.Root>
<Flex
justify='between'
align='center'
gap={4}
sx={{
[mqu.sm]: {
flexDirection: 'column',
alignItems: 'stretch',
},
}}
elementDescriptor={descriptors.apiKeysHeader}
>
<Box elementDescriptor={descriptors.apiKeysSearchBox}>
<SearchInput
name='apiKeysSearch'
placeholder={t(localizationKeys('apiKeys.action__search'))}
aria-label={t(localizationKeys('apiKeys.action__search'))}
value={searchValue}
onChange={e => setSearchValue(e.target.value)}
onClear={() => setSearchValue('')}
elementDescriptor={descriptors.apiKeysSearchInput}
/>
</Box>
{((isOrg && canManageAPIKeys) || !isOrg) && (
<Action.Trigger
value='add-api-key'
hideOnActive={false}
>
<Button
variant='solid'
localizationKey={localizationKeys('apiKeys.action__add')}
elementDescriptor={descriptors.apiKeysAddButton}
/>
</Action.Trigger>
)}
</Flex>
<Action.Open value='add-api-key'>
<Flex sx={t => ({ paddingTop: t.space.$6, paddingBottom: t.space.$6 })}>
<Action.Card sx={{ width: '100%' }}>
<CreateAPIKeyForm onCreate={handleCreateAPIKey} />
</Action.Card>
</Flex>
</Action.Open>
<CopyAPIKeyModal
isOpen={isCopyModalOpen}
onOpen={() => setIsCopyModalOpen(true)}
onClose={() => setIsCopyModalOpen(false)}
apiKeyName={apiKey?.name || ''}
apiKeySecret={apiKey?.secret || ''}
modalRoot={revokeModalRoot}
/>
</Action.Root>
<APIKeysTable
rows={apiKeys}
isLoading={isLoading}
onRevoke={handleRevoke}
elementDescriptor={descriptors.apiKeysTable}
canManageAPIKeys={(isOrg && canManageAPIKeys) || !isOrg}
/>
{pageCount > 1 && (
<Pagination
count={pageCount}
page={Math.min(page, pageCount)}
onChange={handlePageChange}
siblingCount={1}
rowInfo={{ allRowsCount: itemCount, startingRow, endingRow }}
/>
)}
<RevokeAPIKeyConfirmationModal
isOpen={isRevokeModalOpen}
onOpen={() => setIsRevokeModalOpen(true)}
onClose={() => {
setSelectedAPIKeyID('');
setSelectedAPIKeyName('');
setIsRevokeModalOpen(false);
}}
apiKeyID={selectedAPIKeyID}
apiKeyName={selectedAPIKeyName}
onRevokeSuccess={invalidateAll}
modalRoot={revokeModalRoot}
/>
</Col>
);
};
const _APIKeys = () => {
const ctx = useAPIKeysContext();
const { user } = useUser();
// Do not use `useOrganization` to avoid triggering the in-app enable organizations prompt in development instance
const organization = __internal_useOrganizationBase();
const subject = organization?.id ?? user?.id ?? '';
return (
<Flow.Root
flow='apiKeys'
sx={{
width: '100%',
}}
>
<APIKeysPage
subject={subject}
perPage={ctx.perPage}
/>
</Flow.Root>
);
};
export const APIKeys = withCoreUserGuard(withCardStateProvider(_APIKeys));