All files / pages/ApiKeys CreateApiKeyDialog.tsx

66.66% Statements 20/30
64.28% Branches 9/14
42.85% Functions 3/7
68.96% Lines 20/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                        1x         65x 65x 65x 65x 65x 65x   65x 2x   2x 2x 2x       2x 2x               2x       65x               65x 2x                                                         63x                                                 14x                                                                          
import { useState } from 'react';
import { AppDialog } from '@/components/common/AppDialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Field, FieldLabel, FieldContent } from '@/components/ui/field';
import { Checkbox } from '@/components/ui/checkbox';
import { apiKeysService } from '@/services/api-keys.service';
import type { APIKeyCreateResponse } from '@/services/api-keys.service';
import { useToast } from '@/hooks/use-toast';
import { CopyToClipboardButton } from './CopyToClipboardButton';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Info, AlertTriangle } from 'lucide-react';
 
interface CreateApiKeyDialogProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    onCreated: () => void;
}
 
export const CreateApiKeyDialog = ({
    open,
    onOpenChange,
    onCreated,
}: CreateApiKeyDialogProps) => {
    const [name, setName] = useState('');
    const [neverExpires, setNeverExpires] = useState(true);
    const [expiresAt, setExpiresAt] = useState('');
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [createdKey, setCreatedKey] = useState<APIKeyCreateResponse | null>(null);
    const { toast } = useToast();
 
    const handleCreate = async () => {
        Iif (!name) return;
 
        setIsSubmitting(true);
        try {
            const response = await apiKeysService.createApiKey({
                name,
                expires_at: neverExpires ? null : expiresAt,
            });
            setCreatedKey(response);
            onCreated();
        } catch (error: any) {
            toast({
                title: 'Error creating API key',
                description: error.response?.data?.detail || 'Something went wrong',
                variant: 'destructive',
            });
        } finally {
            setIsSubmitting(false);
        }
    };
 
    const resetAndClose = () => {
        setName('');
        setNeverExpires(true);
        setExpiresAt('');
        setCreatedKey(null);
        onOpenChange(false);
    };
 
    if (createdKey) {
        return (
            <AppDialog
                open={open}
                onOpenChange={resetAndClose}
                title="API Key Created"
                description="Copy your API key now. You won't be able to see it again!"
                className="sm:max-w-md"
                footer={
                    <Button onClick={resetAndClose}>I've saved my key</Button>
                }
            >
                <div className="space-y-4">
                    <Alert variant="destructive" className="bg-amber-50 border-amber-200 text-amber-900">
                        <AlertTriangle className="h-4 w-4 text-amber-600" />
                        <AlertTitle>Important Security Warning</AlertTitle>
                        <AlertDescription>
                            This key provides full superadmin access. Store it securely and never share it.
                        </AlertDescription>
                    </Alert>
 
                    <div className="flex items-center space-x-2 bg-slate-100 p-3 rounded border font-mono text-sm break-all">
                        <span className="flex-1 select-all">{createdKey.key}</span>
                        <CopyToClipboardButton value={createdKey.key} label="API Key" />
                    </div>
                </div>
            </AppDialog>
        );
    }
 
    return (
        <AppDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Create API Key"
            description="Generate a persistent key for programmatic superadmin access."
            className="sm:max-w-md"
            footer={
                <>
                    <Button variant="ghost" onClick={() => onOpenChange(false)}>
                        Cancel
                    </Button>
                    <Button onClick={handleCreate} disabled={!name || isSubmitting}>
                        {isSubmitting ? 'Creating...' : 'Create Key'}
                    </Button>
                </>
            }
        >
            <div className="space-y-4">
                <Field>
                    <FieldLabel>Key Name <span className="text-destructive">*</span></FieldLabel>
                    <FieldContent>
                        <Input
                            placeholder="e.g. CI/CD Deployment Key"
                            value={name}
                            onChange={(e) => setName(e.target.value)}
                        />
                    </FieldContent>
                </Field>
 
                <div className="flex items-center space-x-2">
                    <Checkbox
                        id="never-expires"
                        checked={neverExpires}
                        onCheckedChange={(checked) => setNeverExpires(checked === true)}
                    />
                    <Label htmlFor="never-expires">Never expires</Label>
                </div>
 
                {!neverExpires && (
                    <Field>
                        <FieldLabel>Expiration Date</FieldLabel>
                        <FieldContent>
                            <Input
                                type="datetime-local"
                                value={expiresAt}
                                onChange={(e) => setExpiresAt(e.target.value)}
                            />
                        </FieldContent>
                    </Field>
                )}
 
                <Alert variant="default" className="bg-blue-50 border-blue-200 text-blue-900">
                    <Info className="h-4 w-4 text-blue-600" />
                    <AlertDescription>
                        API keys allow bypassing JWT authentication for automated tasks.
                    </AlertDescription>
                </Alert>
            </div>
        </AppDialog>
    );
};