Apply new eslint rules; default to prettier for styling

This commit is contained in:
DaneEveritt 2022-06-26 15:13:52 -04:00
parent f22cce8881
commit dc84af9937
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
218 changed files with 3876 additions and 3564 deletions

View file

@ -16,16 +16,16 @@ import { useFlashKey } from '@/plugins/useFlash';
import Code from '@/components/elements/Code';
export default () => {
const [ deleteIdentifier, setDeleteIdentifier ] = useState('');
const [ keys, setKeys ] = useState<ApiKey[]>([]);
const [ loading, setLoading ] = useState(true);
const [deleteIdentifier, setDeleteIdentifier] = useState('');
const [keys, setKeys] = useState<ApiKey[]>([]);
const [loading, setLoading] = useState(true);
const { clearAndAddHttpError } = useFlashKey('account');
useEffect(() => {
getApiKeys()
.then(keys => setKeys(keys))
.then((keys) => setKeys(keys))
.then(() => setLoading(false))
.catch(error => clearAndAddHttpError(error));
.catch((error) => clearAndAddHttpError(error));
}, []);
const doDeletion = (identifier: string) => {
@ -33,10 +33,8 @@ export default () => {
clearAndAddHttpError();
deleteApiKey(identifier)
.then(() => setKeys(s => ([
...(s || []).filter(key => key.identifier !== identifier),
])))
.catch(error => clearAndAddHttpError(error))
.then(() => setKeys((s) => [...(s || []).filter((key) => key.identifier !== identifier)]))
.catch((error) => clearAndAddHttpError(error))
.then(() => {
setLoading(false);
setDeleteIdentifier('');
@ -45,13 +43,13 @@ export default () => {
return (
<PageContentBlock title={'Account API'}>
<FlashMessageRender byKey={'account'}/>
<FlashMessageRender byKey={'account'} />
<div css={tw`md:flex flex-nowrap my-10`}>
<ContentBox title={'Create API Key'} css={tw`flex-none w-full md:w-1/2`}>
<CreateApiKeyForm onKeyCreated={key => setKeys(s => ([ ...s!, key ]))}/>
<CreateApiKeyForm onKeyCreated={(key) => setKeys((s) => [...s!, key])} />
</ContentBox>
<ContentBox title={'API Keys'} css={tw`flex-1 overflow-hidden mt-8 md:mt-0 md:ml-8`}>
<SpinnerOverlay visible={loading}/>
<SpinnerOverlay visible={loading} />
<Dialog.Confirm
title={'Delete API Key'}
confirm={'Delete Key'}
@ -61,42 +59,36 @@ export default () => {
>
All requests using the <Code>{deleteIdentifier}</Code> key will be invalidated.
</Dialog.Confirm>
{
keys.length === 0 ?
<p css={tw`text-center text-sm`}>
{loading ? 'Loading...' : 'No API keys exist for this account.'}
</p>
:
keys.map((key, index) => (
<GreyRowBox
key={key.identifier}
css={[ tw`bg-neutral-600 flex items-center`, index > 0 && tw`mt-2` ]}
>
<FontAwesomeIcon icon={faKey} css={tw`text-neutral-300`}/>
<div css={tw`ml-4 flex-1 overflow-hidden`}>
<p css={tw`text-sm break-words`}>{key.description}</p>
<p css={tw`text-2xs text-neutral-300 uppercase`}>
Last used:&nbsp;
{key.lastUsedAt ? format(key.lastUsedAt, 'MMM do, yyyy HH:mm') : 'Never'}
</p>
</div>
<p css={tw`text-sm ml-4 hidden md:block`}>
<code css={tw`font-mono py-1 px-2 bg-neutral-900 rounded`}>
{key.identifier}
</code>
{keys.length === 0 ? (
<p css={tw`text-center text-sm`}>
{loading ? 'Loading...' : 'No API keys exist for this account.'}
</p>
) : (
keys.map((key, index) => (
<GreyRowBox
key={key.identifier}
css={[tw`bg-neutral-600 flex items-center`, index > 0 && tw`mt-2`]}
>
<FontAwesomeIcon icon={faKey} css={tw`text-neutral-300`} />
<div css={tw`ml-4 flex-1 overflow-hidden`}>
<p css={tw`text-sm break-words`}>{key.description}</p>
<p css={tw`text-2xs text-neutral-300 uppercase`}>
Last used:&nbsp;
{key.lastUsedAt ? format(key.lastUsedAt, 'MMM do, yyyy HH:mm') : 'Never'}
</p>
<button
css={tw`ml-4 p-2 text-sm`}
onClick={() => setDeleteIdentifier(key.identifier)}
>
<FontAwesomeIcon
icon={faTrashAlt}
css={tw`text-neutral-400 hover:text-red-400 transition-colors duration-150`}
/>
</button>
</GreyRowBox>
))
}
</div>
<p css={tw`text-sm ml-4 hidden md:block`}>
<code css={tw`font-mono py-1 px-2 bg-neutral-900 rounded`}>{key.identifier}</code>
</p>
<button css={tw`ml-4 p-2 text-sm`} onClick={() => setDeleteIdentifier(key.identifier)}>
<FontAwesomeIcon
icon={faTrashAlt}
css={tw`text-neutral-400 hover:text-red-400 transition-colors duration-150`}
/>
</button>
</GreyRowBox>
))
)}
</ContentBox>
</div>
</PageContentBlock>

View file

@ -11,19 +11,19 @@ import MessageBox from '@/components/MessageBox';
import { useLocation } from 'react-router-dom';
const Container = styled.div`
${tw`flex flex-wrap`};
${tw`flex flex-wrap`};
& > div {
${tw`w-full`};
& > div {
${tw`w-full`};
${breakpoint('sm')`
${breakpoint('sm')`
width: calc(50% - 1rem);
`}
${breakpoint('md')`
${breakpoint('md')`
${tw`w-auto flex-1`};
`}
}
}
`;
export default () => {
@ -31,28 +31,23 @@ export default () => {
return (
<PageContentBlock title={'Account Overview'}>
{state?.twoFactorRedirect &&
<MessageBox title={'2-Factor Required'} type={'error'}>
Your account must have two-factor authentication enabled in order to continue.
</MessageBox>
}
{state?.twoFactorRedirect && (
<MessageBox title={'2-Factor Required'} type={'error'}>
Your account must have two-factor authentication enabled in order to continue.
</MessageBox>
)}
<Container css={[ tw`lg:grid lg:grid-cols-3 mb-10`, state?.twoFactorRedirect ? tw`mt-4` : tw`mt-10` ]}>
<Container css={[tw`lg:grid lg:grid-cols-3 mb-10`, state?.twoFactorRedirect ? tw`mt-4` : tw`mt-10`]}>
<ContentBox title={'Update Password'} showFlashes={'account:password'}>
<UpdatePasswordForm/>
<UpdatePasswordForm />
</ContentBox>
<ContentBox
css={tw`mt-8 sm:mt-0 sm:ml-8`}
title={'Update Email Address'}
showFlashes={'account:email'}
>
<UpdateEmailAddressForm/>
<ContentBox css={tw`mt-8 sm:mt-0 sm:ml-8`} title={'Update Email Address'} showFlashes={'account:email'}>
<UpdateEmailAddressForm />
</ContentBox>
<ContentBox css={tw`md:ml-8 mt-8 md:mt-0`} title={'Configure Two Factor'}>
<ConfigureTwoFactorForm/>
<ConfigureTwoFactorForm />
</ContentBox>
</Container>
</PageContentBlock>
);
};

View file

@ -20,7 +20,9 @@ const ApiKeyModal = ({ apiKey }: Props) => {
shown again.
</p>
<pre css={tw`text-sm bg-neutral-900 rounded py-2 px-4 font-mono`}>
<CopyOnClick text={apiKey}><code css={tw`font-mono`}>{apiKey}</code></CopyOnClick>
<CopyOnClick text={apiKey}>
<code css={tw`font-mono`}>{apiKey}</code>
</CopyOnClick>
</pre>
<div css={tw`flex justify-end mt-6`}>
<Button type={'button'} onClick={() => dismiss()}>

View file

@ -18,15 +18,15 @@ export default () => {
const { search } = useLocation();
const defaultPage = Number(new URLSearchParams(search).get('page') || '1');
const [ page, setPage ] = useState((!isNaN(defaultPage) && defaultPage > 0) ? defaultPage : 1);
const [page, setPage] = useState(!isNaN(defaultPage) && defaultPage > 0 ? defaultPage : 1);
const { clearFlashes, clearAndAddHttpError } = useFlash();
const uuid = useStoreState(state => state.user.data!.uuid);
const rootAdmin = useStoreState(state => state.user.data!.rootAdmin);
const [ showOnlyAdmin, setShowOnlyAdmin ] = usePersistedState(`${uuid}:show_all_servers`, false);
const uuid = useStoreState((state) => state.user.data!.uuid);
const rootAdmin = useStoreState((state) => state.user.data!.rootAdmin);
const [showOnlyAdmin, setShowOnlyAdmin] = usePersistedState(`${uuid}:show_all_servers`, false);
const { data: servers, error } = useSWR<PaginatedResult<Server>>(
[ '/api/client/servers', (showOnlyAdmin && rootAdmin), page ],
() => getServers({ page, type: (showOnlyAdmin && rootAdmin) ? 'admin' : undefined }),
['/api/client/servers', showOnlyAdmin && rootAdmin, page],
() => getServers({ page, type: showOnlyAdmin && rootAdmin ? 'admin' : undefined })
);
useEffect(() => {
@ -34,58 +34,53 @@ export default () => {
if (servers.pagination.currentPage > 1 && !servers.items.length) {
setPage(1);
}
}, [ servers?.pagination.currentPage ]);
}, [servers?.pagination.currentPage]);
useEffect(() => {
// Don't use react-router to handle changing this part of the URL, otherwise it
// triggers a needless re-render. We just want to track this in the URL incase the
// user refreshes the page.
window.history.replaceState(null, document.title, `/${page <= 1 ? '' : `?page=${page}`}`);
}, [ page ]);
}, [page]);
useEffect(() => {
if (error) clearAndAddHttpError({ key: 'dashboard', error });
if (!error) clearFlashes('dashboard');
}, [ error ]);
}, [error]);
return (
<PageContentBlock title={'Dashboard'} showFlashKey={'dashboard'}>
{rootAdmin &&
<div css={tw`mb-2 flex justify-end items-center`}>
<p css={tw`uppercase text-xs text-neutral-400 mr-2`}>
{showOnlyAdmin ? 'Showing others\' servers' : 'Showing your servers'}
</p>
<Switch
name={'show_all_servers'}
defaultChecked={showOnlyAdmin}
onChange={() => setShowOnlyAdmin(s => !s)}
/>
</div>
}
{!servers ?
<Spinner centered size={'large'}/>
:
{rootAdmin && (
<div css={tw`mb-2 flex justify-end items-center`}>
<p css={tw`uppercase text-xs text-neutral-400 mr-2`}>
{showOnlyAdmin ? "Showing others' servers" : 'Showing your servers'}
</p>
<Switch
name={'show_all_servers'}
defaultChecked={showOnlyAdmin}
onChange={() => setShowOnlyAdmin((s) => !s)}
/>
</div>
)}
{!servers ? (
<Spinner centered size={'large'} />
) : (
<Pagination data={servers} onPageSelect={setPage}>
{({ items }) => (
items.length > 0 ?
{({ items }) =>
items.length > 0 ? (
items.map((server, index) => (
<ServerRow
key={server.uuid}
server={server}
css={index > 0 ? tw`mt-2` : undefined}
/>
<ServerRow key={server.uuid} server={server} css={index > 0 ? tw`mt-2` : undefined} />
))
:
) : (
<p css={tw`text-center text-sm text-neutral-400`}>
{showOnlyAdmin ?
'There are no other servers to display.'
:
'There are no servers associated with your account.'
}
{showOnlyAdmin
? 'There are no other servers to display.'
: 'There are no servers associated with your account.'}
</p>
)}
)
}
</Pagination>
}
)}
</PageContentBlock>
);
};

View file

@ -13,15 +13,18 @@ import isEqual from 'react-fast-compare';
// Determines if the current value is in an alarm threshold so we can show it in red rather
// than the more faded default style.
const isAlarmState = (current: number, limit: number): boolean => limit > 0 && (current / (limit * 1024 * 1024) >= 0.90);
const isAlarmState = (current: number, limit: number): boolean => limit > 0 && current / (limit * 1024 * 1024) >= 0.9;
const Icon = memo(styled(FontAwesomeIcon)<{ $alarm: boolean }>`
${props => props.$alarm ? tw`text-red-400` : tw`text-neutral-500`};
`, isEqual);
const Icon = memo(
styled(FontAwesomeIcon)<{ $alarm: boolean }>`
${(props) => (props.$alarm ? tw`text-red-400` : tw`text-neutral-500`)};
`,
isEqual
);
const IconDescription = styled.p<{ $alarm: boolean }>`
${tw`text-sm ml-2`};
${props => props.$alarm ? tw`text-white` : tw`text-neutral-400`};
${(props) => (props.$alarm ? tw`text-white` : tw`text-neutral-400`)};
`;
const StatusIndicatorBox = styled(GreyRowBox)<{ $status: ServerPowerState | undefined }>`
@ -31,7 +34,12 @@ const StatusIndicatorBox = styled(GreyRowBox)<{ $status: ServerPowerState | unde
${tw`w-2 bg-red-500 absolute right-0 z-20 rounded-full m-1 opacity-50 transition-all duration-150`};
height: calc(100% - 0.5rem);
${({ $status }) => (!$status || $status === 'offline') ? tw`bg-red-500` : ($status === 'running' ? tw`bg-green-500` : tw`bg-yellow-500`)};
${({ $status }) =>
!$status || $status === 'offline'
? tw`bg-red-500`
: $status === 'running'
? tw`bg-green-500`
: tw`bg-yellow-500`};
}
&:hover .status-bar {
@ -41,16 +49,17 @@ const StatusIndicatorBox = styled(GreyRowBox)<{ $status: ServerPowerState | unde
export default ({ server, className }: { server: Server; className?: string }) => {
const interval = useRef<number>(null);
const [ isSuspended, setIsSuspended ] = useState(server.status === 'suspended');
const [ stats, setStats ] = useState<ServerStats | null>(null);
const [isSuspended, setIsSuspended] = useState(server.status === 'suspended');
const [stats, setStats] = useState<ServerStats | null>(null);
const getStats = () => getServerResourceUsage(server.uuid)
.then(data => setStats(data))
.catch(error => console.error(error));
const getStats = () =>
getServerResourceUsage(server.uuid)
.then((data) => setStats(data))
.catch((error) => console.error(error));
useEffect(() => {
setIsSuspended(stats?.isSuspended || server.status === 'suspended');
}, [ stats?.isSuspended, server.status ]);
}, [stats?.isSuspended, server.status]);
useEffect(() => {
// Don't waste a HTTP request if there is nothing important to show to the user because
@ -65,11 +74,11 @@ export default ({ server, className }: { server: Server; className?: string }) =
return () => {
interval.current && clearInterval(interval.current);
};
}, [ isSuspended ]);
}, [isSuspended]);
const alarms = { cpu: false, memory: false, disk: false };
if (stats) {
alarms.cpu = server.limits.cpu === 0 ? false : (stats.cpuUsagePercent >= (server.limits.cpu * 0.9));
alarms.cpu = server.limits.cpu === 0 ? false : stats.cpuUsagePercent >= server.limits.cpu * 0.9;
alarms.memory = isAlarmState(stats.memoryUsageInBytes, server.limits.memory);
alarms.disk = server.limits.disk === 0 ? false : isAlarmState(stats.diskUsageInBytes, server.limits.disk);
}
@ -82,60 +91,57 @@ export default ({ server, className }: { server: Server; className?: string }) =
<StatusIndicatorBox as={Link} to={`/server/${server.id}`} className={className} $status={stats?.status}>
<div css={tw`flex items-center col-span-12 sm:col-span-5 lg:col-span-6`}>
<div className={'icon'} css={tw`mr-4`}>
<FontAwesomeIcon icon={faServer}/>
<FontAwesomeIcon icon={faServer} />
</div>
<div>
<p css={tw`text-lg break-words`}>{server.name}</p>
{!!server.description &&
<p css={tw`text-sm text-neutral-300 break-words line-clamp-2`}>{server.description}</p>
}
{!!server.description && (
<p css={tw`text-sm text-neutral-300 break-words line-clamp-2`}>{server.description}</p>
)}
</div>
</div>
<div css={tw`flex-1 ml-4 lg:block lg:col-span-2 hidden`}>
<div css={tw`flex justify-center`}>
<FontAwesomeIcon icon={faEthernet} css={tw`text-neutral-500`}/>
<FontAwesomeIcon icon={faEthernet} css={tw`text-neutral-500`} />
<p css={tw`text-sm text-neutral-400 ml-2`}>
{
server.allocations.filter(alloc => alloc.isDefault).map(allocation => (
{server.allocations
.filter((alloc) => alloc.isDefault)
.map((allocation) => (
<React.Fragment key={allocation.ip + allocation.port.toString()}>
{allocation.alias || ip(allocation.ip)}:{allocation.port}
</React.Fragment>
))
}
))}
</p>
</div>
</div>
<div css={tw`hidden col-span-7 lg:col-span-4 sm:flex items-baseline justify-center`}>
{(!stats || isSuspended) ?
isSuspended ?
{!stats || isSuspended ? (
isSuspended ? (
<div css={tw`flex-1 text-center`}>
<span css={tw`bg-red-500 rounded px-2 py-1 text-red-100 text-xs`}>
{server.status === 'suspended' ? 'Suspended' : 'Connection Error'}
</span>
</div>
:
(server.isTransferring || server.status) ?
<div css={tw`flex-1 text-center`}>
<span css={tw`bg-neutral-500 rounded px-2 py-1 text-neutral-100 text-xs`}>
{server.isTransferring ?
'Transferring'
:
server.status === 'installing' ? 'Installing' : (
server.status === 'restoring_backup' ?
'Restoring Backup'
:
'Unavailable'
)
}
</span>
</div>
:
<Spinner size={'small'}/>
:
) : server.isTransferring || server.status ? (
<div css={tw`flex-1 text-center`}>
<span css={tw`bg-neutral-500 rounded px-2 py-1 text-neutral-100 text-xs`}>
{server.isTransferring
? 'Transferring'
: server.status === 'installing'
? 'Installing'
: server.status === 'restoring_backup'
? 'Restoring Backup'
: 'Unavailable'}
</span>
</div>
) : (
<Spinner size={'small'} />
)
) : (
<React.Fragment>
<div css={tw`flex-1 ml-4 sm:block hidden`}>
<div css={tw`flex justify-center`}>
<Icon icon={faMicrochip} $alarm={alarms.cpu}/>
<Icon icon={faMicrochip} $alarm={alarms.cpu} />
<IconDescription $alarm={alarms.cpu}>
{stats.cpuUsagePercent.toFixed(2)} %
</IconDescription>
@ -144,7 +150,7 @@ export default ({ server, className }: { server: Server; className?: string }) =
</div>
<div css={tw`flex-1 ml-4 sm:block hidden`}>
<div css={tw`flex justify-center`}>
<Icon icon={faMemory} $alarm={alarms.memory}/>
<Icon icon={faMemory} $alarm={alarms.memory} />
<IconDescription $alarm={alarms.memory}>
{bytesToString(stats.memoryUsageInBytes)}
</IconDescription>
@ -153,7 +159,7 @@ export default ({ server, className }: { server: Server; className?: string }) =
</div>
<div css={tw`flex-1 ml-4 sm:block hidden`}>
<div css={tw`flex justify-center`}>
<Icon icon={faHdd} $alarm={alarms.disk}/>
<Icon icon={faHdd} $alarm={alarms.disk} />
<IconDescription $alarm={alarms.disk}>
{bytesToString(stats.diskUsageInBytes)}
</IconDescription>
@ -161,9 +167,9 @@ export default ({ server, className }: { server: Server; className?: string }) =
<p css={tw`text-xs text-neutral-600 text-center mt-1`}>of {diskLimit}</p>
</div>
</React.Fragment>
}
)}
</div>
<div className={'status-bar'}/>
<div className={'status-bar'} />
</StatusIndicatorBox>
);
};

View file

@ -16,53 +16,57 @@ import useLocationHash from '@/plugins/useLocationHash';
export default () => {
const { hash } = useLocationHash();
const { clearAndAddHttpError } = useFlashKey('account');
const [ filters, setFilters ] = useState<ActivityLogFilters>({ page: 1, sorts: { timestamp: -1 } });
const [filters, setFilters] = useState<ActivityLogFilters>({ page: 1, sorts: { timestamp: -1 } });
const { data, isValidating, error } = useActivityLogs(filters, {
revalidateOnMount: true,
revalidateOnFocus: false,
});
useEffect(() => {
setFilters(value => ({ ...value, filters: { ip: hash.ip, event: hash.event } }));
}, [ hash ]);
setFilters((value) => ({ ...value, filters: { ip: hash.ip, event: hash.event } }));
}, [hash]);
useEffect(() => {
clearAndAddHttpError(error);
}, [ error ]);
}, [error]);
return (
<PageContentBlock title={'Account Activity Log'}>
<FlashMessageRender byKey={'account'}/>
{(filters.filters?.event || filters.filters?.ip) &&
<FlashMessageRender byKey={'account'} />
{(filters.filters?.event || filters.filters?.ip) && (
<div className={'flex justify-end mb-2'}>
<Link
to={'#'}
className={classNames(btnStyles.button, btnStyles.text, 'w-full sm:w-auto')}
onClick={() => setFilters(value => ({ ...value, filters: {} }))}
onClick={() => setFilters((value) => ({ ...value, filters: {} }))}
>
Clear Filters <XCircleIcon className={'w-4 h-4 ml-2'}/>
Clear Filters <XCircleIcon className={'w-4 h-4 ml-2'} />
</Link>
</div>
}
{!data && isValidating ?
<Spinner centered/>
:
)}
{!data && isValidating ? (
<Spinner centered />
) : (
<div className={'bg-gray-700'}>
{data?.items.map((activity) => (
<ActivityLogEntry key={activity.timestamp.toString() + activity.event} activity={activity}>
{typeof activity.properties.useragent === 'string' &&
{typeof activity.properties.useragent === 'string' && (
<Tooltip content={activity.properties.useragent} placement={'top'}>
<span><DesktopComputerIcon/></span>
<span>
<DesktopComputerIcon />
</span>
</Tooltip>
}
)}
</ActivityLogEntry>
))}
</div>
}
{data && <PaginationFooter
pagination={data.pagination}
onPageSelect={page => setFilters(value => ({ ...value, page }))}
/>}
)}
{data && (
<PaginationFooter
pagination={data.pagination}
onPageSelect={(page) => setFilters((value) => ({ ...value, page }))}
/>
)}
</PageContentBlock>
);
};

View file

@ -7,23 +7,21 @@ import tw from 'twin.macro';
import Button from '@/components/elements/Button';
export default () => {
const [ visible, setVisible ] = useState(false);
const [visible, setVisible] = useState(false);
const isEnabled = useStoreState((state: ApplicationStore) => state.user.data!.useTotp);
return (
<div>
{visible && (
isEnabled ?
<DisableTwoFactorModal visible={visible} onModalDismissed={() => setVisible(false)}/>
:
<SetupTwoFactorModal visible={visible} onModalDismissed={() => setVisible(false)}/>
)}
{visible &&
(isEnabled ? (
<DisableTwoFactorModal visible={visible} onModalDismissed={() => setVisible(false)} />
) : (
<SetupTwoFactorModal visible={visible} onModalDismissed={() => setVisible(false)} />
))}
<p css={tw`text-sm`}>
{isEnabled ?
'Two-factor authentication is currently enabled on your account.'
:
'You do not currently have two-factor authentication enabled on your account. Click the button below to begin configuring it.'
}
{isEnabled
? 'Two-factor authentication is currently enabled on your account.'
: 'You do not currently have two-factor authentication enabled on your account. Click the button below to begin configuring it.'}
</p>
<div css={tw`mt-6`}>
<Button color={'red'} isSecondary onClick={() => setVisible(true)}>

View file

@ -19,10 +19,12 @@ interface Values {
allowedIps: string;
}
const CustomTextarea = styled(Textarea)`${tw`h-32`}`;
const CustomTextarea = styled(Textarea)`
${tw`h-32`}
`;
export default ({ onKeyCreated }: { onKeyCreated: (key: ApiKey) => void }) => {
const [ apiKey, setApiKey ] = useState('');
const [apiKey, setApiKey] = useState('');
const { addError, clearFlashes } = useStoreActions((actions: Actions<ApplicationStore>) => actions.flashes);
const submit = (values: Values, { setSubmitting, resetForm }: FormikHelpers<Values>) => {
@ -34,7 +36,7 @@ export default ({ onKeyCreated }: { onKeyCreated: (key: ApiKey) => void }) => {
setApiKey(`${key.identifier}${secretToken}`);
onKeyCreated(key);
})
.catch(error => {
.catch((error) => {
console.error(error);
addError({ key: 'account', message: httpErrorToHuman(error) });
@ -44,11 +46,7 @@ export default ({ onKeyCreated }: { onKeyCreated: (key: ApiKey) => void }) => {
return (
<>
<ApiKeyModal
visible={apiKey.length > 0}
onModalDismissed={() => setApiKey('')}
apiKey={apiKey}
/>
<ApiKeyModal visible={apiKey.length > 0} onModalDismissed={() => setApiKey('')} apiKey={apiKey} />
<Formik
onSubmit={submit}
initialValues={{ description: '', allowedIps: '' }}
@ -59,21 +57,23 @@ export default ({ onKeyCreated }: { onKeyCreated: (key: ApiKey) => void }) => {
>
{({ isSubmitting }) => (
<Form>
<SpinnerOverlay visible={isSubmitting}/>
<SpinnerOverlay visible={isSubmitting} />
<FormikFieldWrapper
label={'Description'}
name={'description'}
description={'A description of this API key.'}
css={tw`mb-6`}
>
<Field name={'description'} as={Input}/>
<Field name={'description'} as={Input} />
</FormikFieldWrapper>
<FormikFieldWrapper
label={'Allowed IPs'}
name={'allowedIps'}
description={'Leave blank to allow any IP address to use this API key, otherwise provide each IP address on a new line.'}
description={
'Leave blank to allow any IP address to use this API key, otherwise provide each IP address on a new line.'
}
>
<Field name={'allowedIps'} as={CustomTextarea}/>
<Field name={'allowedIps'} as={CustomTextarea} />
</FormikFieldWrapper>
<div css={tw`flex justify-end mt-6`}>
<Button>Create</Button>

View file

@ -27,7 +27,7 @@ const DisableTwoFactorModal = () => {
updateUserData({ useTotp: false });
dismiss();
})
.catch(error => {
.catch((error) => {
console.error(error);
clearAndAddHttpError({ error, key: 'account:two-factor' });
@ -48,13 +48,15 @@ const DisableTwoFactorModal = () => {
>
{({ isValid }) => (
<Form className={'mb-0'}>
<FlashMessageRender css={tw`mb-6`} byKey={'account:two-factor'}/>
<FlashMessageRender css={tw`mb-6`} byKey={'account:two-factor'} />
<Field
id={'password'}
name={'password'}
type={'password'}
label={'Current Password'}
description={'In order to disable two-factor authentication you will need to provide your account password.'}
description={
'In order to disable two-factor authentication you will need to provide your account password.'
}
autoFocus
/>
<div css={tw`mt-6 text-right`}>

View file

@ -19,8 +19,8 @@ interface Values {
}
const SetupTwoFactorModal = () => {
const [ token, setToken ] = useState<TwoFactorTokenData | null>(null);
const [ recoveryTokens, setRecoveryTokens ] = useState<string[]>([]);
const [token, setToken] = useState<TwoFactorTokenData | null>(null);
const [recoveryTokens, setRecoveryTokens] = useState<string[]>([]);
const { dismiss, setPropOverrides } = useContext(ModalContext);
const updateUserData = useStoreActions((actions: Actions<ApplicationStore>) => actions.user.updateUserData);
@ -29,31 +29,31 @@ const SetupTwoFactorModal = () => {
useEffect(() => {
getTwoFactorTokenData()
.then(setToken)
.catch(error => {
.catch((error) => {
console.error(error);
clearAndAddHttpError({ error, key: 'account:two-factor' });
});
}, []);
const submit = ({ code }: Values, { setSubmitting }: FormikHelpers<Values>) => {
setPropOverrides(state => ({ ...state, showSpinnerOverlay: true }));
setPropOverrides((state) => ({ ...state, showSpinnerOverlay: true }));
enableAccountTwoFactor(code)
.then(tokens => {
.then((tokens) => {
setRecoveryTokens(tokens);
})
.catch(error => {
.catch((error) => {
console.error(error);
clearAndAddHttpError({ error, key: 'account:two-factor' });
})
.then(() => {
setSubmitting(false);
setPropOverrides(state => ({ ...state, showSpinnerOverlay: false }));
setPropOverrides((state) => ({ ...state, showSpinnerOverlay: false }));
});
};
useEffect(() => {
setPropOverrides(state => ({
setPropOverrides((state) => ({
...state,
closeOnEscape: !recoveryTokens.length,
closeOnBackground: !recoveryTokens.length,
@ -64,7 +64,7 @@ const SetupTwoFactorModal = () => {
updateUserData({ useTotp: true });
}
};
}, [ recoveryTokens ]);
}, [recoveryTokens]);
return (
<Formik
@ -76,20 +76,24 @@ const SetupTwoFactorModal = () => {
.matches(/^(\d){6}$/, 'Authenticator code must be 6 digits.'),
})}
>
{recoveryTokens.length > 0 ?
{recoveryTokens.length > 0 ? (
<>
<h2 css={tw`text-2xl mb-4`}>Two-factor authentication enabled</h2>
<p css={tw`text-neutral-300`}>
Two-factor authentication has been enabled on your account. Should you lose access to
your authenticator device, you&apos;ll need to use one of the codes displayed below in order to access your
account.
Two-factor authentication has been enabled on your account. Should you lose access to your
authenticator device, you&apos;ll need to use one of the codes displayed below in order to
access your account.
</p>
<p css={tw`text-neutral-300 mt-4`}>
<strong>These codes will not be displayed again.</strong> Please take note of them now
by storing them in a secure repository such as a password manager.
<strong>These codes will not be displayed again.</strong> Please take note of them now by
storing them in a secure repository such as a password manager.
</p>
<pre css={tw`text-sm mt-4 rounded font-mono bg-neutral-900 p-4`}>
{recoveryTokens.map(token => <code key={token} css={tw`block mb-1`}>{token}</code>)}
{recoveryTokens.map((token) => (
<code key={token} css={tw`block mb-1`}>
{token}
</code>
))}
</pre>
<div css={tw`text-right`}>
<Button css={tw`mt-6`} onClick={dismiss}>
@ -97,24 +101,26 @@ const SetupTwoFactorModal = () => {
</Button>
</div>
</>
:
) : (
<Form css={tw`mb-0`}>
<FlashMessageRender css={tw`mb-6`} byKey={'account:two-factor'}/>
<FlashMessageRender css={tw`mb-6`} byKey={'account:two-factor'} />
<div css={tw`flex flex-wrap`}>
<div css={tw`w-full md:flex-1`}>
<div css={tw`w-32 h-32 md:w-64 md:h-64 bg-neutral-600 p-2 rounded mx-auto`}>
{!token ?
{!token ? (
<img
src={'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='}
src={
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='
}
css={tw`w-64 h-64 rounded`}
/>
:
) : (
<QRCode
renderAs={'svg'}
value={token.image_url_data}
css={tw`w-full h-full shadow-none rounded-none`}
/>
}
)}
</div>
</div>
<div css={tw`w-full mt-6 md:mt-0 md:flex-1 md:flex md:flex-col`}>
@ -124,20 +130,20 @@ const SetupTwoFactorModal = () => {
name={'code'}
type={'text'}
title={'Code From Authenticator'}
description={'Enter the code from your authenticator device after scanning the QR image.'}
description={
'Enter the code from your authenticator device after scanning the QR image.'
}
/>
{token &&
<div css={tw`mt-4 pt-4 border-t border-neutral-500 text-neutral-200`}>
Alternatively, enter the following token into your authenticator application:
<CopyOnClick text={token.secret}>
<div css={tw`text-sm bg-neutral-900 rounded mt-2 py-2 px-4 font-mono`}>
<code css={tw`font-mono`}>
{token.secret}
</code>
</div>
</CopyOnClick>
</div>
}
{token && (
<div css={tw`mt-4 pt-4 border-t border-neutral-500 text-neutral-200`}>
Alternatively, enter the following token into your authenticator application:
<CopyOnClick text={token.secret}>
<div css={tw`text-sm bg-neutral-900 rounded mt-2 py-2 px-4 font-mono`}>
<code css={tw`font-mono`}>{token.secret}</code>
</div>
</CopyOnClick>
</div>
)}
</div>
<div css={tw`mt-6 md:mt-0 text-right`}>
<Button>Setup</Button>
@ -145,7 +151,7 @@ const SetupTwoFactorModal = () => {
</div>
</div>
</Form>
}
)}
</Formik>
);
};

View file

@ -29,17 +29,21 @@ export default () => {
clearFlashes('account:email');
updateEmail({ ...values })
.then(() => addFlash({
type: 'success',
key: 'account:email',
message: 'Your primary email has been updated.',
}))
.catch(error => addFlash({
type: 'error',
key: 'account:email',
title: 'Error',
message: httpErrorToHuman(error),
}))
.then(() =>
addFlash({
type: 'success',
key: 'account:email',
message: 'Your primary email has been updated.',
})
)
.catch((error) =>
addFlash({
type: 'error',
key: 'account:email',
title: 'Error',
message: httpErrorToHuman(error),
})
)
.then(() => {
resetForm();
setSubmitting(false);
@ -47,39 +51,28 @@ export default () => {
};
return (
<Formik
onSubmit={submit}
validationSchema={schema}
initialValues={{ email: user!.email, password: '' }}
>
{
({ isSubmitting, isValid }) => (
<React.Fragment>
<SpinnerOverlay size={'large'} visible={isSubmitting}/>
<Form css={tw`m-0`}>
<Formik onSubmit={submit} validationSchema={schema} initialValues={{ email: user!.email, password: '' }}>
{({ isSubmitting, isValid }) => (
<React.Fragment>
<SpinnerOverlay size={'large'} visible={isSubmitting} />
<Form css={tw`m-0`}>
<Field id={'current_email'} type={'email'} name={'email'} label={'Email'} />
<div css={tw`mt-6`}>
<Field
id={'current_email'}
type={'email'}
name={'email'}
label={'Email'}
id={'confirm_password'}
type={'password'}
name={'password'}
label={'Confirm Password'}
/>
<div css={tw`mt-6`}>
<Field
id={'confirm_password'}
type={'password'}
name={'password'}
label={'Confirm Password'}
/>
</div>
<div css={tw`mt-6`}>
<Button size={'small'} disabled={isSubmitting || !isValid}>
Update Email
</Button>
</div>
</Form>
</React.Fragment>
)
}
</div>
<div css={tw`mt-6`}>
<Button size={'small'} disabled={isSubmitting || !isValid}>
Update Email
</Button>
</div>
</Form>
</React.Fragment>
)}
</Formik>
);
};

View file

@ -19,9 +19,13 @@ interface Values {
const schema = Yup.object().shape({
current: Yup.string().min(1).required('You must provide your current password.'),
password: Yup.string().min(8).required(),
confirmPassword: Yup.string().test('password', 'Password confirmation does not match the password you entered.', function (value) {
return value === this.parent.password;
}),
confirmPassword: Yup.string().test(
'password',
'Password confirmation does not match the password you entered.',
function (value) {
return value === this.parent.password;
}
),
});
export default () => {
@ -39,12 +43,14 @@ export default () => {
// @ts-ignore
window.location = '/auth/login';
})
.catch(error => addFlash({
key: 'account:password',
type: 'error',
title: 'Error',
message: httpErrorToHuman(error),
}))
.catch((error) =>
addFlash({
key: 'account:password',
type: 'error',
title: 'Error',
message: httpErrorToHuman(error),
})
)
.then(() => setSubmitting(false));
};
@ -55,43 +61,43 @@ export default () => {
validationSchema={schema}
initialValues={{ current: '', password: '', confirmPassword: '' }}
>
{
({ isSubmitting, isValid }) => (
<React.Fragment>
<SpinnerOverlay size={'large'} visible={isSubmitting}/>
<Form css={tw`m-0`}>
{({ isSubmitting, isValid }) => (
<React.Fragment>
<SpinnerOverlay size={'large'} visible={isSubmitting} />
<Form css={tw`m-0`}>
<Field
id={'current_password'}
type={'password'}
name={'current'}
label={'Current Password'}
/>
<div css={tw`mt-6`}>
<Field
id={'current_password'}
id={'new_password'}
type={'password'}
name={'current'}
label={'Current Password'}
name={'password'}
label={'New Password'}
description={
'Your new password should be at least 8 characters in length and unique to this website.'
}
/>
<div css={tw`mt-6`}>
<Field
id={'new_password'}
type={'password'}
name={'password'}
label={'New Password'}
description={'Your new password should be at least 8 characters in length and unique to this website.'}
/>
</div>
<div css={tw`mt-6`}>
<Field
id={'confirm_new_password'}
type={'password'}
name={'confirmPassword'}
label={'Confirm New Password'}
/>
</div>
<div css={tw`mt-6`}>
<Button size={'small'} disabled={isSubmitting || !isValid}>
Update Password
</Button>
</div>
</Form>
</React.Fragment>
)
}
</div>
<div css={tw`mt-6`}>
<Field
id={'confirm_new_password'}
type={'password'}
name={'confirmPassword'}
label={'Confirm New Password'}
/>
</div>
<div css={tw`mt-6`}>
<Button size={'small'} disabled={isSubmitting || !isValid}>
Update Password
</Button>
</div>
</Form>
</React.Fragment>
)}
</Formik>
</React.Fragment>
);

View file

@ -6,10 +6,10 @@ import SearchModal from '@/components/dashboard/search/SearchModal';
import Tooltip from '@/components/elements/tooltip/Tooltip';
export default () => {
const [ visible, setVisible ] = useState(false);
const [visible, setVisible] = useState(false);
useEventListener('keydown', (e: KeyboardEvent) => {
if ([ 'input', 'textarea' ].indexOf(((e.target as HTMLElement).tagName || 'input').toLowerCase()) < 0) {
if (['input', 'textarea'].indexOf(((e.target as HTMLElement).tagName || 'input').toLowerCase()) < 0) {
if (!visible && e.metaKey && e.key.toLowerCase() === '/') {
setVisible(true);
}
@ -18,16 +18,10 @@ export default () => {
return (
<>
{visible &&
<SearchModal
appear
visible={visible}
onDismissed={() => setVisible(false)}
/>
}
{visible && <SearchModal appear visible={visible} onDismissed={() => setVisible(false)} />}
<Tooltip placement={'bottom'} content={'Search'}>
<div className={'navigation-link'} onClick={() => setVisible(true)}>
<FontAwesomeIcon icon={faSearch}/>
<FontAwesomeIcon icon={faSearch} />
</div>
</Tooltip>
</>

View file

@ -40,24 +40,26 @@ const SearchWatcher = () => {
if (values.term.length >= 3) {
submitForm();
}
}, [ values.term ]);
}, [values.term]);
return null;
};
export default ({ ...props }: Props) => {
const ref = useRef<HTMLInputElement>(null);
const isAdmin = useStoreState(state => state.user.data!.rootAdmin);
const [ servers, setServers ] = useState<Server[]>([]);
const { clearAndAddHttpError, clearFlashes } = useStoreActions((actions: Actions<ApplicationStore>) => actions.flashes);
const isAdmin = useStoreState((state) => state.user.data!.rootAdmin);
const [servers, setServers] = useState<Server[]>([]);
const { clearAndAddHttpError, clearFlashes } = useStoreActions(
(actions: Actions<ApplicationStore>) => actions.flashes
);
const search = debounce(({ term }: Values, { setSubmitting }: FormikHelpers<Values>) => {
clearFlashes('search');
// if (ref.current) ref.current.focus();
getServers({ query: term, type: isAdmin ? 'admin-all' : undefined })
.then(servers => setServers(servers.items.filter((_, index) => index < 5)))
.catch(error => {
.then((servers) => setServers(servers.items.filter((_, index) => index < 5)))
.catch((error) => {
console.error(error);
clearAndAddHttpError({ key: 'search', error });
})
@ -69,10 +71,10 @@ export default ({ ...props }: Props) => {
if (props.visible) {
if (ref.current) ref.current.focus();
}
}, [ props.visible ]);
}, [props.visible]);
// Formik does not support an innerRef on custom components.
const InputWithRef = (props: any) => <Input autoFocus {...props} ref={ref}/>;
const InputWithRef = (props: any) => <Input autoFocus {...props} ref={ref} />;
return (
<Formik
@ -90,16 +92,15 @@ export default ({ ...props }: Props) => {
label={'Search term'}
description={'Enter a server name, uuid, or allocation to begin searching.'}
>
<SearchWatcher/>
<SearchWatcher />
<InputSpinner visible={isSubmitting}>
<Field as={InputWithRef} name={'term'}/>
<Field as={InputWithRef} name={'term'} />
</InputSpinner>
</FormikFieldWrapper>
</Form>
{servers.length > 0 &&
<div css={tw`mt-6`}>
{
servers.map(server => (
{servers.length > 0 && (
<div css={tw`mt-6`}>
{servers.map((server) => (
<ServerResult
key={server.uuid}
to={`/server/${server.id}`}
@ -108,11 +109,13 @@ export default ({ ...props }: Props) => {
<div css={tw`flex-1 mr-4`}>
<p css={tw`text-sm`}>{server.name}</p>
<p css={tw`mt-1 text-xs text-neutral-400`}>
{
server.allocations.filter(alloc => alloc.isDefault).map(allocation => (
<span key={allocation.ip + allocation.port.toString()}>{allocation.alias || ip(allocation.ip)}:{allocation.port}</span>
))
}
{server.allocations
.filter((alloc) => alloc.isDefault)
.map((allocation) => (
<span key={allocation.ip + allocation.port.toString()}>
{allocation.alias || ip(allocation.ip)}:{allocation.port}
</span>
))}
</p>
</div>
<div css={tw`flex-none text-right`}>
@ -121,10 +124,9 @@ export default ({ ...props }: Props) => {
</span>
</div>
</ServerResult>
))
}
</div>
}
))}
</div>
)}
</Modal>
)}
</Formik>

View file

@ -22,43 +22,40 @@ export default () => {
useEffect(() => {
clearAndAddHttpError(error);
}, [ error ]);
}, [error]);
return (
<PageContentBlock title={'Account API'}>
<FlashMessageRender byKey={'account'}/>
<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/>
<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:&nbsp;
{format(key.createdAt, 'MMM do, yyyy HH:mm')}
</p>
</div>
<DeleteSSHKeyButton name={key.name} fingerprint={key.fingerprint} />
</GreyRowBox>
))
}
<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:&nbsp;
{format(key.createdAt, 'MMM do, yyyy HH:mm')}
</p>
</div>
<DeleteSSHKeyButton name={key.name} fingerprint={key.fingerprint} />
</GreyRowBox>
))
)}
</ContentBox>
</div>
</PageContentBlock>

View file

@ -15,7 +15,9 @@ interface Values {
publicKey: string;
}
const CustomTextarea = styled(Textarea)`${tw`h-32`}`;
const CustomTextarea = styled(Textarea)`
${tw`h-32`}
`;
export default () => {
const { clearAndAddHttpError } = useFlashKey('account');
@ -45,16 +47,16 @@ export default () => {
>
{({ isSubmitting }) => (
<Form>
<SpinnerOverlay visible={isSubmitting}/>
<SpinnerOverlay visible={isSubmitting} />
<FormikFieldWrapper label={'SSH Key Name'} name={'name'} css={tw`mb-6`}>
<Field name={'name'} as={Input}/>
<Field name={'name'} as={Input} />
</FormikFieldWrapper>
<FormikFieldWrapper
label={'Public Key'}
name={'publicKey'}
description={'Enter your public SSH key.'}
>
<Field name={'publicKey'} as={CustomTextarea}/>
<Field name={'publicKey'} as={CustomTextarea} />
</FormikFieldWrapper>
<div css={tw`flex justify-end mt-6`}>
<Button>Save</Button>

View file

@ -9,7 +9,7 @@ import Code from '@/components/elements/Code';
export default ({ name, fingerprint }: { name: string; fingerprint: string }) => {
const { clearAndAddHttpError } = useFlashKey('account');
const [ visible, setVisible ] = useState(false);
const [visible, setVisible] = useState(false);
const { mutate } = useSSHKeys();
const onClick = () => {
@ -18,11 +18,10 @@ export default ({ name, fingerprint }: { name: string; fingerprint: string }) =>
Promise.all([
mutate((data) => data?.filter((value) => value.fingerprint !== fingerprint), false),
deleteSSHKey(fingerprint),
])
.catch((error) => {
mutate(undefined, true).catch(console.error);
clearAndAddHttpError(error);
});
]).catch((error) => {
mutate(undefined, true).catch(console.error);
clearAndAddHttpError(error);
});
};
return (