-
Notifications
You must be signed in to change notification settings - Fork 259
Expand file tree
/
Copy pathapiKeysPage.tsx
More file actions
285 lines (260 loc) · 12.5 KB
/
apiKeysPage.tsx
File metadata and controls
285 lines (260 loc) · 12.5 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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
'use client';
import { createApiKey, getUserApiKeys } from "@/actions";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { isServiceError } from "@/lib/utils";
import { Copy, Check, AlertTriangle, Loader2, Plus } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useToast } from "@/components/hooks/use-toast";
import useCaptureEvent from "@/hooks/useCaptureEvent";
import { DataTable } from "@/components/ui/data-table";
import { columns, ApiKeyColumnInfo } from "./columns";
import { Skeleton } from "@/components/ui/skeleton";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
export function ApiKeysPage({ canCreateApiKey }: { canCreateApiKey: boolean }) {
const { toast } = useToast();
const captureEvent = useCaptureEvent();
const [apiKeys, setApiKeys] = useState<{ name: string; createdAt: Date; lastUsedAt: Date | null }[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
const [newKeyName, setNewKeyName] = useState("");
const [isCreatingKey, setIsCreatingKey] = useState(false);
const [newlyCreatedKey, setNewlyCreatedKey] = useState<string | null>(null);
const [copySuccess, setCopySuccess] = useState(false);
const [error, setError] = useState<string | null>(null);
const loadApiKeys = useCallback(async () => {
setIsLoading(true);
setError(null);
try {
const keys = await getUserApiKeys();
if (isServiceError(keys)) {
setError("Failed to load API keys");
toast({
title: "Error",
description: "Failed to load API keys",
variant: "destructive",
});
return;
}
setApiKeys(keys);
} catch (error) {
console.error(error);
setError("Failed to load API keys");
toast({
title: "Error",
description: "Failed to load API keys",
variant: "destructive",
});
} finally {
setIsLoading(false);
}
}, [toast]);
useEffect(() => {
loadApiKeys();
}, [loadApiKeys]);
const handleCreateApiKey = async () => {
if (!newKeyName.trim()) {
toast({
title: "Error",
description: "API key name cannot be empty",
variant: "destructive",
});
return;
}
setIsCreatingKey(true);
try {
const result = await createApiKey(newKeyName.trim());
if (isServiceError(result)) {
toast({
title: "Error",
description: `Failed to create API key: ${result.message}`,
variant: "destructive",
});
captureEvent('wa_api_key_creation_fail', {});
return;
}
setNewlyCreatedKey(result.key);
await loadApiKeys();
captureEvent('wa_api_key_created', {});
} catch (error) {
console.error(error);
toast({
title: "Error",
description: `Failed to create API key: ${error}`,
variant: "destructive",
});
captureEvent('wa_api_key_creation_fail', {});
} finally {
setIsCreatingKey(false);
}
};
const handleCopyApiKey = () => {
if (!newlyCreatedKey) return;
navigator.clipboard.writeText(newlyCreatedKey)
.then(() => {
setCopySuccess(true);
setTimeout(() => setCopySuccess(false), 2000);
})
.catch(() => {
toast({
title: "Error",
description: "Failed to copy API key to clipboard",
variant: "destructive",
});
});
};
const handleCloseDialog = () => {
setIsCreateDialogOpen(false);
setNewKeyName("");
setNewlyCreatedKey(null);
setCopySuccess(false);
};
const tableData = useMemo(() => {
if (isLoading) return Array(4).fill(null).map(() => ({
name: "",
createdAt: "",
lastUsedAt: null,
}));
if (!apiKeys) return [];
return apiKeys.map((key): ApiKeyColumnInfo => ({
name: key.name,
createdAt: key.createdAt.toISOString(),
lastUsedAt: key.lastUsedAt?.toISOString() ?? null,
})).sort((a, b) => {
return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
});
}, [apiKeys, isLoading]);
const tableColumns = useMemo(() => {
if (isLoading) {
return columns().map((column) => {
if ('accessorKey' in column && column.accessorKey === "name") {
return {
...column,
cell: () => (
<div className="flex items-center gap-2">
<Skeleton className="h-4 w-4 rounded-md" /> {/* Icon skeleton */}
<Skeleton className="h-4 w-48" /> {/* Name skeleton */}
</div>
),
}
}
return {
...column,
cell: () => <Skeleton className="h-4 w-24" />,
}
})
}
return columns();
}, [isLoading]);
if (error) {
return <div>Error loading API keys</div>;
}
return (
<div className="flex flex-col gap-6">
<div className="flex flex-row items-center justify-between">
<div>
<h3 className="text-lg font-medium">API Keys</h3>
<p className="text-sm text-muted-foreground max-w-lg">
Create and manage API keys for programmatic access to Sourcebot. All API keys are scoped to the user who created them.
</p>
</div>
<TooltipProvider>
<Tooltip>
{!canCreateApiKey && (
<TooltipContent>
API key creation is restricted.
</TooltipContent>
)}
<TooltipTrigger asChild>
<span className={!canCreateApiKey ? "cursor-not-allowed" : undefined}>
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
<DialogTrigger asChild>
<Button
disabled={!canCreateApiKey}
className={!canCreateApiKey ? "pointer-events-none" : undefined}
onClick={() => {
setNewlyCreatedKey(null);
setNewKeyName("");
setIsCreateDialogOpen(true);
}}
>
<Plus className="h-4 w-4 mr-2" />
Create API Key
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>{newlyCreatedKey ? 'Your New API Key' : 'Create API Key'}</DialogTitle>
</DialogHeader>
{newlyCreatedKey ? (
<div className="space-y-4">
<div className="flex items-center gap-2 p-3 border border-yellow-200 dark:border-yellow-800 bg-yellow-50 dark:bg-yellow-900/20 rounded-md text-yellow-700 dark:text-yellow-400">
<AlertTriangle className="h-5 w-5 flex-shrink-0" />
<p className="text-sm">
This is the only time you'll see this API key. Make sure to copy it now.
</p>
</div>
<div className="flex items-center space-x-2">
<div className="bg-muted p-2 rounded-md text-sm flex-1 break-all font-mono">
{newlyCreatedKey}
</div>
<Button
size="icon"
variant="outline"
onClick={handleCopyApiKey}
>
{copySuccess ? (
<Check className="h-4 w-4 text-green-500" />
) : (
<Copy className="h-4 w-4" />
)}
</Button>
</div>
</div>
) : (
<div className="py-4">
<Input
value={newKeyName}
onChange={(e) => setNewKeyName(e.target.value)}
placeholder="Enter a name for your API key"
className="mb-2"
/>
</div>
)}
<DialogFooter className="sm:justify-between">
{newlyCreatedKey ? (
<Button onClick={handleCloseDialog}>
Done
</Button>
) : (
<>
<Button variant="outline" onClick={handleCloseDialog}>
Cancel
</Button>
<Button
onClick={handleCreateApiKey}
disabled={isCreatingKey || !newKeyName.trim()}
>
{isCreatingKey && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
Create
</Button>
</>
)}
</DialogFooter>
</DialogContent>
</Dialog>
</span>
</TooltipTrigger>
</Tooltip>
</TooltipProvider>
</div>
<DataTable
columns={tableColumns}
data={tableData}
searchKey="name"
searchPlaceholder="Search API keys..."
/>
</div>
);
}