Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pterodactyl
GitHub Repository: pterodactyl/panel
Path: blob/develop/resources/scripts/components/dashboard/forms/CreateApiKeyForm.tsx
7454 views
1
import { useState } from 'react';
2
import { Field, Form, Formik, FormikHelpers } from 'formik';
3
import { object, string } from 'yup';
4
import FormikFieldWrapper from '@/components/elements/FormikFieldWrapper';
5
import createApiKey from '@/api/account/createApiKey';
6
import { Actions, useStoreActions } from 'easy-peasy';
7
import { ApplicationStore } from '@/state';
8
import { httpErrorToHuman } from '@/api/http';
9
import SpinnerOverlay from '@/components/elements/SpinnerOverlay';
10
import { ApiKey } from '@/api/account/getApiKeys';
11
import tw from 'twin.macro';
12
import Button from '@/components/elements/Button';
13
import Input, { Textarea } from '@/components/elements/Input';
14
import styled from 'styled-components';
15
import ApiKeyModal from '@/components/dashboard/ApiKeyModal';
16
17
interface Values {
18
description: string;
19
allowedIps: string;
20
}
21
22
const CustomTextarea = styled(Textarea)`
23
${tw`h-32`}
24
`;
25
26
export default ({ onKeyCreated }: { onKeyCreated: (key: ApiKey) => void }) => {
27
const [apiKey, setApiKey] = useState('');
28
const { addError, clearFlashes } = useStoreActions((actions: Actions<ApplicationStore>) => actions.flashes);
29
30
const submit = (values: Values, { setSubmitting, resetForm }: FormikHelpers<Values>) => {
31
clearFlashes('account');
32
createApiKey(values.description, values.allowedIps)
33
.then(({ secretToken, ...key }) => {
34
resetForm();
35
setSubmitting(false);
36
setApiKey(`${key.identifier}${secretToken}`);
37
onKeyCreated(key);
38
})
39
.catch(error => {
40
console.error(error);
41
42
addError({ key: 'account', message: httpErrorToHuman(error) });
43
setSubmitting(false);
44
});
45
};
46
47
return (
48
<>
49
<ApiKeyModal visible={apiKey.length > 0} onModalDismissed={() => setApiKey('')} apiKey={apiKey} />
50
<Formik
51
onSubmit={submit}
52
initialValues={{ description: '', allowedIps: '' }}
53
validationSchema={object().shape({
54
allowedIps: string(),
55
description: string().required().min(4),
56
})}
57
>
58
{({ isSubmitting }) => (
59
<Form>
60
<SpinnerOverlay visible={isSubmitting} />
61
<FormikFieldWrapper
62
label={'Description'}
63
name={'description'}
64
description={'A description of this API key.'}
65
css={tw`mb-6`}
66
>
67
<Field name={'description'} as={Input} />
68
</FormikFieldWrapper>
69
<FormikFieldWrapper
70
label={'Allowed IPs'}
71
name={'allowedIps'}
72
description={
73
'Leave blank to allow any IP address to use this API key, otherwise provide each IP address on a new line.'
74
}
75
>
76
<Field name={'allowedIps'} as={CustomTextarea} />
77
</FormikFieldWrapper>
78
<div css={tw`flex justify-end mt-6`}>
79
<Button>Create</Button>
80
</div>
81
</Form>
82
)}
83
</Formik>
84
</>
85
);
86
};
87
88