Add support for storing SSH keys on user accounts
This commit is contained in:
parent
5705d7dbdd
commit
97280a62a2
20 changed files with 678 additions and 6 deletions
28
resources/scripts/api/account/ssh-keys.ts
Normal file
28
resources/scripts/api/account/ssh-keys.ts
Normal file
|
@ -0,0 +1,28 @@
|
|||
import useSWR, { ConfigInterface } from 'swr';
|
||||
import useUserSWRContentKey from '@/plugins/useUserSWRContentKey';
|
||||
import http, { FractalResponseList } from '@/api/http';
|
||||
import { SSHKey, Transformers } from '@definitions/user';
|
||||
import { AxiosError } from 'axios';
|
||||
|
||||
const useSSHKeys = (config?: ConfigInterface<SSHKey[], AxiosError>) => {
|
||||
const key = useUserSWRContentKey([ 'account', 'ssh-keys' ]);
|
||||
|
||||
return useSWR(key, async () => {
|
||||
const { data } = await http.get('/api/client/account/ssh-keys');
|
||||
|
||||
return (data as FractalResponseList).data.map((datum: any) => {
|
||||
return Transformers.toSSHKey(datum.attributes);
|
||||
});
|
||||
}, { revalidateOnMount: false, ...(config || {}) });
|
||||
};
|
||||
|
||||
const createSSHKey = async (name: string, publicKey: string): Promise<SSHKey> => {
|
||||
const { data } = await http.post('/api/client/account/ssh-keys', { name, public_key: publicKey });
|
||||
|
||||
return Transformers.toSSHKey(data.attributes);
|
||||
};
|
||||
|
||||
const deleteSSHKey = async (fingerprint: string): Promise<void> =>
|
||||
await http.delete(`/api/client/account/ssh-keys/${fingerprint}`);
|
||||
|
||||
export { useSSHKeys, createSSHKey, deleteSSHKey };
|
|
@ -1,2 +1,8 @@
|
|||
// empty export
|
||||
export type _T = string;
|
||||
import { Model } from '@/api/definitions';
|
||||
|
||||
interface SSHKey extends Model {
|
||||
name: string;
|
||||
publicKey: string;
|
||||
fingerprint: string;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
|
|
@ -1,4 +1,14 @@
|
|||
import { SSHKey } from '@definitions/user/models';
|
||||
|
||||
export default class Transformers {
|
||||
static toSSHKey (data: Record<any, any>): SSHKey {
|
||||
return {
|
||||
name: data.name,
|
||||
publicKey: data.public_key,
|
||||
fingerprint: data.fingerprint,
|
||||
createdAt: new Date(data.created_at),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export class MetaTransformers {
|
||||
|
|
|
@ -0,0 +1,66 @@
|
|||
import React, { useEffect } from 'react';
|
||||
import ContentBox from '@/components/elements/ContentBox';
|
||||
import SpinnerOverlay from '@/components/elements/SpinnerOverlay';
|
||||
import FlashMessageRender from '@/components/FlashMessageRender';
|
||||
import PageContentBlock from '@/components/elements/PageContentBlock';
|
||||
import tw from 'twin.macro';
|
||||
import GreyRowBox from '@/components/elements/GreyRowBox';
|
||||
import { useSSHKeys } from '@/api/account/ssh-keys';
|
||||
import { useFlashKey } from '@/plugins/useFlash';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import { faKey } from '@fortawesome/free-solid-svg-icons';
|
||||
import { format } from 'date-fns';
|
||||
import CreateSSHKeyForm from '@/components/dashboard/ssh/CreateSSHKeyForm';
|
||||
import DeleteSSHKeyButton from '@/components/dashboard/ssh/DeleteSSHKeyButton';
|
||||
|
||||
export default () => {
|
||||
const { clearAndAddHttpError } = useFlashKey('account');
|
||||
const { data, isValidating, error } = useSSHKeys({
|
||||
revalidateOnMount: true,
|
||||
revalidateOnFocus: false,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
clearAndAddHttpError(error);
|
||||
}, [ error ]);
|
||||
|
||||
return (
|
||||
<PageContentBlock title={'Account API'}>
|
||||
<FlashMessageRender byKey={'account'}/>
|
||||
<div css={tw`md:flex flex-nowrap my-10`}>
|
||||
<ContentBox title={'Add SSH Key'} css={tw`flex-none w-full md:w-1/2`}>
|
||||
<CreateSSHKeyForm/>
|
||||
</ContentBox>
|
||||
<ContentBox title={'SSH Keys'} css={tw`flex-1 overflow-hidden mt-8 md:mt-0 md:ml-8`}>
|
||||
<SpinnerOverlay visible={!data && isValidating}/>
|
||||
{
|
||||
!data || !data.length ?
|
||||
<p css={tw`text-center text-sm`}>
|
||||
{!data ? 'Loading...' : 'No SSH Keys exist for this account.'}
|
||||
</p>
|
||||
:
|
||||
data.map((key, index) => (
|
||||
<GreyRowBox
|
||||
key={key.fingerprint}
|
||||
css={[ tw`bg-neutral-600 flex space-x-4 items-center`, index > 0 && tw`mt-2` ]}
|
||||
>
|
||||
<FontAwesomeIcon icon={faKey} css={tw`text-neutral-300`}/>
|
||||
<div css={tw`flex-1`}>
|
||||
<p css={tw`text-sm break-words font-medium`}>{key.name}</p>
|
||||
<p css={tw`text-xs mt-1 font-mono truncate`}>
|
||||
SHA256:{key.fingerprint}
|
||||
</p>
|
||||
<p css={tw`text-xs mt-1 text-neutral-300 uppercase`}>
|
||||
Added on:
|
||||
{format(key.createdAt, 'MMM do, yyyy HH:mm')}
|
||||
</p>
|
||||
</div>
|
||||
<DeleteSSHKeyButton fingerprint={key.fingerprint} />
|
||||
</GreyRowBox>
|
||||
))
|
||||
}
|
||||
</ContentBox>
|
||||
</div>
|
||||
</PageContentBlock>
|
||||
);
|
||||
};
|
|
@ -0,0 +1,67 @@
|
|||
import React from 'react';
|
||||
import { Field, Form, Formik, FormikHelpers } from 'formik';
|
||||
import { object, string } from 'yup';
|
||||
import FormikFieldWrapper from '@/components/elements/FormikFieldWrapper';
|
||||
import SpinnerOverlay from '@/components/elements/SpinnerOverlay';
|
||||
import tw from 'twin.macro';
|
||||
import Button from '@/components/elements/Button';
|
||||
import Input, { Textarea } from '@/components/elements/Input';
|
||||
import styled from 'styled-components/macro';
|
||||
import { useFlashKey } from '@/plugins/useFlash';
|
||||
import { createSSHKey, useSSHKeys } from '@/api/account/ssh-keys';
|
||||
|
||||
interface Values {
|
||||
name: string;
|
||||
publicKey: string;
|
||||
}
|
||||
|
||||
const CustomTextarea = styled(Textarea)`${tw`h-32`}`;
|
||||
|
||||
export default () => {
|
||||
const { clearAndAddHttpError } = useFlashKey('account');
|
||||
const { mutate } = useSSHKeys();
|
||||
|
||||
const submit = (values: Values, { setSubmitting, resetForm }: FormikHelpers<Values>) => {
|
||||
clearAndAddHttpError();
|
||||
|
||||
createSSHKey(values.name, values.publicKey)
|
||||
.then((key) => {
|
||||
resetForm();
|
||||
mutate((data) => (data || []).concat(key));
|
||||
})
|
||||
.catch((error) => clearAndAddHttpError(error))
|
||||
.then(() => setSubmitting(false));
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Formik
|
||||
onSubmit={submit}
|
||||
initialValues={{ name: '', publicKey: '' }}
|
||||
validationSchema={object().shape({
|
||||
name: string().required(),
|
||||
publicKey: string().required(),
|
||||
})}
|
||||
>
|
||||
{({ isSubmitting }) => (
|
||||
<Form>
|
||||
<SpinnerOverlay visible={isSubmitting}/>
|
||||
<FormikFieldWrapper label={'SSH Key Name'} name={'name'} css={tw`mb-6`}>
|
||||
<Field name={'name'} as={Input}/>
|
||||
</FormikFieldWrapper>
|
||||
<FormikFieldWrapper
|
||||
label={'Public Key'}
|
||||
name={'publicKey'}
|
||||
description={'Enter your public SSH key.'}
|
||||
>
|
||||
<Field name={'publicKey'} as={CustomTextarea}/>
|
||||
</FormikFieldWrapper>
|
||||
<div css={tw`flex justify-end mt-6`}>
|
||||
<Button>Save</Button>
|
||||
</div>
|
||||
</Form>
|
||||
)}
|
||||
</Formik>
|
||||
</>
|
||||
);
|
||||
};
|
|
@ -0,0 +1,46 @@
|
|||
import tw from 'twin.macro';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import { faTrashAlt } from '@fortawesome/free-solid-svg-icons';
|
||||
import React, { useState } from 'react';
|
||||
import { useFlashKey } from '@/plugins/useFlash';
|
||||
import ConfirmationModal from '@/components/elements/ConfirmationModal';
|
||||
import { deleteSSHKey, useSSHKeys } from '@/api/account/ssh-keys';
|
||||
|
||||
export default ({ fingerprint }: { fingerprint: string }) => {
|
||||
const { clearAndAddHttpError } = useFlashKey('account');
|
||||
const [ visible, setVisible ] = useState(false);
|
||||
const { mutate } = useSSHKeys();
|
||||
|
||||
const onClick = () => {
|
||||
clearAndAddHttpError();
|
||||
|
||||
Promise.all([
|
||||
mutate((data) => data?.filter((value) => value.fingerprint !== fingerprint), false),
|
||||
deleteSSHKey(fingerprint),
|
||||
])
|
||||
.catch((error) => {
|
||||
mutate(undefined, true);
|
||||
clearAndAddHttpError(error);
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<ConfirmationModal
|
||||
visible={visible}
|
||||
title={'Confirm Key Deletion'}
|
||||
buttonText={'Yes, Delete SSH Key'}
|
||||
onConfirmed={onClick}
|
||||
onModalDismissed={() => setVisible(false)}
|
||||
>
|
||||
Are you sure you wish to delete this SSH key?
|
||||
</ConfirmationModal>
|
||||
<button css={tw`ml-4 p-2 text-sm`} onClick={() => setVisible(true)}>
|
||||
<FontAwesomeIcon
|
||||
icon={faTrashAlt}
|
||||
css={tw`text-neutral-400 hover:text-red-400 transition-colors duration-150`}
|
||||
/>
|
||||
</button>
|
||||
</>
|
||||
);
|
||||
};
|
|
@ -2,8 +2,23 @@ import { Actions, useStoreActions } from 'easy-peasy';
|
|||
import { FlashStore } from '@/state/flashes';
|
||||
import { ApplicationStore } from '@/state';
|
||||
|
||||
interface KeyedFlashStore {
|
||||
clearFlashes: () => void;
|
||||
clearAndAddHttpError: (error?: Error | string | null) => void;
|
||||
}
|
||||
|
||||
const useFlash = (): Actions<FlashStore> => {
|
||||
return useStoreActions((actions: Actions<ApplicationStore>) => actions.flashes);
|
||||
};
|
||||
|
||||
const useFlashKey = (key: string): KeyedFlashStore => {
|
||||
const { clearFlashes, clearAndAddHttpError } = useFlash();
|
||||
|
||||
return {
|
||||
clearFlashes: () => clearFlashes(key),
|
||||
clearAndAddHttpError: (error) => clearAndAddHttpError({ key, error }),
|
||||
};
|
||||
};
|
||||
|
||||
export { useFlashKey };
|
||||
export default useFlash;
|
||||
|
|
12
resources/scripts/plugins/useUserSWRContentKey.ts
Normal file
12
resources/scripts/plugins/useUserSWRContentKey.ts
Normal file
|
@ -0,0 +1,12 @@
|
|||
import { useStoreState } from '@/state/hooks';
|
||||
|
||||
export default (context: string | string[]) => {
|
||||
const key = Array.isArray(context) ? context.join(':') : context;
|
||||
const uuid = useStoreState(state => state.user.data?.uuid);
|
||||
|
||||
if (!key.trim().length) {
|
||||
throw new Error('Must provide a valid context key to "useUserSWRContextKey".');
|
||||
}
|
||||
|
||||
return `swr::${uuid || 'unknown'}:${key.trim()}`;
|
||||
};
|
|
@ -7,6 +7,7 @@ import AccountApiContainer from '@/components/dashboard/AccountApiContainer';
|
|||
import { NotFound } from '@/components/elements/ScreenBlock';
|
||||
import TransitionRouter from '@/TransitionRouter';
|
||||
import SubNavigation from '@/components/elements/SubNavigation';
|
||||
import AccountSSHContainer from '@/components/dashboard/ssh/AccountSSHContainer';
|
||||
|
||||
export default ({ location }: RouteComponentProps) => (
|
||||
<>
|
||||
|
@ -16,6 +17,7 @@ export default ({ location }: RouteComponentProps) => (
|
|||
<div>
|
||||
<NavLink to={'/account'} exact>Settings</NavLink>
|
||||
<NavLink to={'/account/api'}>API Credentials</NavLink>
|
||||
<NavLink to={'/account/ssh'}>SSH Keys</NavLink>
|
||||
</div>
|
||||
</SubNavigation>
|
||||
}
|
||||
|
@ -30,6 +32,9 @@ export default ({ location }: RouteComponentProps) => (
|
|||
<Route path={'/account/api'} exact>
|
||||
<AccountApiContainer/>
|
||||
</Route>
|
||||
<Route path={'/account/ssh'} exact>
|
||||
<AccountSSHContainer/>
|
||||
</Route>
|
||||
<Route path={'*'}>
|
||||
<NotFound/>
|
||||
</Route>
|
||||
|
|
|
@ -6,7 +6,7 @@ export interface FlashStore {
|
|||
items: FlashMessage[];
|
||||
addFlash: Action<FlashStore, FlashMessage>;
|
||||
addError: Action<FlashStore, { message: string; key?: string }>;
|
||||
clearAndAddHttpError: Action<FlashStore, { error: any, key?: string }>;
|
||||
clearAndAddHttpError: Action<FlashStore, { error?: Error | any | null; key?: string }>;
|
||||
clearFlashes: Action<FlashStore, string | void>;
|
||||
}
|
||||
|
||||
|
@ -29,8 +29,19 @@ const flashes: FlashStore = {
|
|||
state.items.push({ type: 'error', title: 'Error', ...payload });
|
||||
}),
|
||||
|
||||
clearAndAddHttpError: action((state, { key, error }) => {
|
||||
state.items = [ { type: 'error', title: 'Error', key, message: httpErrorToHuman(error) } ];
|
||||
clearAndAddHttpError: action((state, payload) => {
|
||||
if (!payload.error) {
|
||||
state.items = [];
|
||||
} else {
|
||||
console.error(payload.error);
|
||||
|
||||
state.items = [ {
|
||||
type: 'error',
|
||||
title: 'Error',
|
||||
key: payload.key,
|
||||
message: httpErrorToHuman(payload.error),
|
||||
} ];
|
||||
}
|
||||
}),
|
||||
|
||||
clearFlashes: action((state, payload) => {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue