import { useState } from 'react'; import { useStore } from '@tanstack/react-form'; import { useAppForm, Form } from '@/components/form'; import type { ApiKeyResource } from '@/api/admin/api-keys/queries'; import { API_KEY_RESOURCES, createAdminApiKeyInput, useCreateAdminApiKey } from '@/api/admin/api-keys/queries'; import { Dialog } from '@/components/elements/dialog'; import SpinnerOverlay from '@/components/elements/SpinnerOverlay'; import Label from '@/components/elements/Label'; import Button from '@/components/elements/Button'; import { NewButton } from '@/components/elements/NewButton'; import CopyOnClick from '@/components/elements/CopyOnClick'; // AdminAcl bitmask values (Read = 1, Write = 2). const PERMISSION_NONE = 0; const PERMISSION_READ = 1; const PERMISSION_READ_WRITE = 3; const labelFor = (resource: ApiKeyResource): string => resource .split('_') .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) .join(' '); const initialPermissions = { servers: PERMISSION_NONE, nodes: PERMISSION_NONE, allocations: PERMISSION_NONE, users: PERMISSION_NONE, locations: PERMISSION_NONE, eggs: PERMISSION_NONE, database_hosts: PERMISSION_NONE, server_databases: PERMISSION_NONE, } satisfies Record; const validateMemo = (value: string): string | undefined => { if (value.length < 1) { return 'A description must be provided.'; } if (value.length > 500) { return 'The description must not exceed 500 characters.'; } return undefined; }; type CreateApiKeyDialogProps = { open: boolean; onClose: () => void; onCreatedSecret: (secret: string) => void; }; function CreateApiKeyDialog({ open, onClose, onCreatedSecret }: CreateApiKeyDialogProps) { const createApiKey = useCreateAdminApiKey(); const form = useAppForm({ defaultValues: { memo: '', permissions: initialPermissions }, onSubmit: async ({ value }) => { try { const apiKey = await createApiKey.mutateAsync(createAdminApiKeyInput(value)); onClose(); onCreatedSecret(apiKey.meta?.secret_token ?? ''); } catch { // Error toast is handled by the mutation. } }, }); const isSubmitting = useStore(form.store, (state) => state.isSubmitting); return (
validateMemo(value), }} > {(field) => ( )}
{API_KEY_RESOURCES.map((resource) => (

{labelFor(resource)}

{(field) => ( )}
))}
Create Key
); } export default function CreateApiKeyButton() { const [secret, setSecret] = useState(''); return ( <> 0} title='Your new API key' onClose={() => setSecret('')}>

The application API key shown below will not be displayed again. Store it somewhere safe before closing this dialog.

                    
                        {secret}
                    
                
New API key}> {({ open, onClose }) => ( )} ); }