Finalize API key management for accounts

This commit is contained in:
Dane Everitt 2020-03-22 19:10:49 -07:00
parent 3ef649d984
commit 8d52e2e1a7
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
6 changed files with 154 additions and 29 deletions

View file

@ -3,11 +3,14 @@
namespace Pterodactyl\Http\Controllers\Api\Client; namespace Pterodactyl\Http\Controllers\Api\Client;
use Pterodactyl\Models\ApiKey; use Pterodactyl\Models\ApiKey;
use Illuminate\Http\JsonResponse;
use Pterodactyl\Exceptions\DisplayException; use Pterodactyl\Exceptions\DisplayException;
use Illuminate\Contracts\Encryption\Encrypter; use Illuminate\Contracts\Encryption\Encrypter;
use Pterodactyl\Services\Api\KeyCreationService; use Pterodactyl\Services\Api\KeyCreationService;
use Pterodactyl\Repositories\Eloquent\ApiKeyRepository;
use Pterodactyl\Http\Requests\Api\Client\ClientApiRequest; use Pterodactyl\Http\Requests\Api\Client\ClientApiRequest;
use Pterodactyl\Transformers\Api\Client\ApiKeyTransformer; use Pterodactyl\Transformers\Api\Client\ApiKeyTransformer;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Pterodactyl\Http\Requests\Api\Client\Account\StoreApiKeyRequest; use Pterodactyl\Http\Requests\Api\Client\Account\StoreApiKeyRequest;
class ApiKeyController extends ClientApiController class ApiKeyController extends ClientApiController
@ -22,18 +25,28 @@ class ApiKeyController extends ClientApiController
*/ */
private $encrypter; private $encrypter;
/**
* @var \Pterodactyl\Repositories\Eloquent\ApiKeyRepository
*/
private $repository;
/** /**
* ApiKeyController constructor. * ApiKeyController constructor.
* *
* @param \Illuminate\Contracts\Encryption\Encrypter $encrypter * @param \Illuminate\Contracts\Encryption\Encrypter $encrypter
* @param \Pterodactyl\Services\Api\KeyCreationService $keyCreationService * @param \Pterodactyl\Services\Api\KeyCreationService $keyCreationService
* @param \Pterodactyl\Repositories\Eloquent\ApiKeyRepository $repository
*/ */
public function __construct(Encrypter $encrypter, KeyCreationService $keyCreationService) public function __construct(
{ Encrypter $encrypter,
KeyCreationService $keyCreationService,
ApiKeyRepository $repository
) {
parent::__construct(); parent::__construct();
$this->encrypter = $encrypter; $this->encrypter = $encrypter;
$this->keyCreationService = $keyCreationService; $this->keyCreationService = $keyCreationService;
$this->repository = $repository;
} }
/** /**
@ -80,7 +93,24 @@ class ApiKeyController extends ClientApiController
->toArray(); ->toArray();
} }
public function delete() /**
* Deletes a given API key.
*
* @param \Pterodactyl\Http\Requests\Api\Client\ClientApiRequest $request
* @param string $identifier
* @return \Illuminate\Http\JsonResponse
*/
public function delete(ClientApiRequest $request, string $identifier)
{ {
$response = $this->repository->deleteWhere([
'user_id' => $request->user()->id,
'identifier' => $identifier,
]);
if (! $response) {
throw new NotFoundHttpException;
}
return JsonResponse::create([], JsonResponse::HTTP_NO_CONTENT);
} }
} }

View file

@ -0,0 +1,9 @@
import http from '@/api/http';
export default (identifier: string): Promise<void> => {
return new Promise((resolve, reject) => {
http.delete(`/api/client/account/api-keys/${identifier}`)
.then(() => resolve())
.catch(reject);
});
};

View file

@ -3,44 +3,96 @@ import ContentBox from '@/components/elements/ContentBox';
import CreateApiKeyForm from '@/components/dashboard/forms/CreateApiKeyForm'; import CreateApiKeyForm from '@/components/dashboard/forms/CreateApiKeyForm';
import getApiKeys, { ApiKey } from '@/api/account/getApiKeys'; import getApiKeys, { ApiKey } from '@/api/account/getApiKeys';
import SpinnerOverlay from '@/components/elements/SpinnerOverlay'; import SpinnerOverlay from '@/components/elements/SpinnerOverlay';
import { Simulate } from 'react-dom/test-utils';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faKey } from '@fortawesome/free-solid-svg-icons/faKey'; import { faKey } from '@fortawesome/free-solid-svg-icons/faKey';
import { faTrashAlt } from '@fortawesome/free-solid-svg-icons/faTrashAlt'; import { faTrashAlt } from '@fortawesome/free-solid-svg-icons/faTrashAlt';
import ConfirmationModal from '@/components/elements/ConfirmationModal';
import deleteApiKey from '@/api/account/deleteApiKey';
import { Actions, useStoreActions } from 'easy-peasy';
import { ApplicationStore } from '@/state';
import FlashMessageRender from '@/components/FlashMessageRender';
import { httpErrorToHuman } from '@/api/http';
import format from 'date-fns/format';
export default () => { export default () => {
const [ deleteIdentifier, setDeleteIdentifier ] = useState('');
const [ keys, setKeys ] = useState<ApiKey[]>([]); const [ keys, setKeys ] = useState<ApiKey[]>([]);
const [ loading, setLoading ] = useState(true); const [ loading, setLoading ] = useState(true);
const { addError, clearFlashes } = useStoreActions((actions: Actions<ApplicationStore>) => actions.flashes);
useEffect(() => { useEffect(() => {
clearFlashes('account');
getApiKeys() getApiKeys()
.then(keys => setKeys(keys)) .then(keys => setKeys(keys))
.then(() => setLoading(false)) .then(() => setLoading(false))
.catch(error => { .catch(error => {
console.error(error); console.error(error);
addError({ key: 'account', message: httpErrorToHuman(error) });
}); });
}, []); }, []);
const doDeletion = (identifier: string) => {
setLoading(true);
clearFlashes('account');
deleteApiKey(identifier)
.then(() => setKeys(s => ([
...(s || []).filter(key => key.identifier !== identifier),
])))
.catch(error => {
console.error(error);
addError({ key: 'account', message: httpErrorToHuman(error) });
})
.then(() => setLoading(false));
};
return ( return (
<div className={'my-10 flex'}> <div className={'my-10 flex'}>
<ContentBox title={'Create API Key'} className={'flex-1'} showFlashes={'account'}> <FlashMessageRender byKey={'account'} className={'mb-4'}/>
<CreateApiKeyForm/> <ContentBox title={'Create API Key'} className={'flex-1'}>
<CreateApiKeyForm onKeyCreated={key => setKeys(s => ([...s!, key]))}/>
</ContentBox> </ContentBox>
<ContentBox title={'API Keys'} className={'ml-10 flex-1'}> <ContentBox title={'API Keys'} className={'ml-10 flex-1'}>
<SpinnerOverlay visible={loading}/> <SpinnerOverlay visible={loading}/>
{deleteIdentifier &&
<ConfirmationModal
title={'Confirm key deletion'}
buttonText={'Yes, delete key'}
visible={true}
onConfirmed={() => {
doDeletion(deleteIdentifier);
setDeleteIdentifier('');
}}
onCanceled={() => setDeleteIdentifier('')}
>
Are you sure you wish to delete this API key? All requests using it will immediately be
invalidated and will fail.
</ConfirmationModal>
}
{ {
keys.length === 0 ?
<p className={'text-center text-sm'}>
{loading ? 'Loading...' : 'No API keys exist for this account.'}
</p>
:
keys.map(key => ( keys.map(key => (
<div key={key.identifier} className={'grey-row-box bg-neutral-600 mb-2 flex items-center'}> <div key={key.identifier} className={'grey-row-box bg-neutral-600 mb-2 flex items-center'}>
<FontAwesomeIcon icon={faKey} className={'text-neutral-300'}/> <FontAwesomeIcon icon={faKey} className={'text-neutral-300'}/>
<p className={'text-sm ml-4 flex-1'}> <div className={'ml-4 flex-1'}>
{key.description} <p className={'text-sm'}>{key.description}</p>
<p className={'text-2xs text-neutral-300 uppercase'}>
Last
used: {key.lastUsedAt ? format(key.lastUsedAt, 'MMM Do, YYYY HH:mm') : 'Never'}
</p> </p>
</div>
<p className={'text-sm ml-4'}> <p className={'text-sm ml-4'}>
<code className={'font-mono py-1 px-2 bg-neutral-900 rounded'}> <code className={'font-mono py-1 px-2 bg-neutral-900 rounded'}>
{key.identifier} {key.identifier}
</code> </code>
</p> </p>
<button className={'ml-4 p-2 text-sm'}> <button
className={'ml-4 p-2 text-sm'}
onClick={() => setDeleteIdentifier(key.identifier)}
>
<FontAwesomeIcon <FontAwesomeIcon
icon={faTrashAlt} icon={faTrashAlt}
className={'text-neutral-400 hover:text-red-400 transition-color duration-150'} className={'text-neutral-400 hover:text-red-400 transition-color duration-150'}

View file

@ -8,23 +8,25 @@ import { Actions, useStoreActions } from 'easy-peasy';
import { ApplicationStore } from '@/state'; import { ApplicationStore } from '@/state';
import { httpErrorToHuman } from '@/api/http'; import { httpErrorToHuman } from '@/api/http';
import SpinnerOverlay from '@/components/elements/SpinnerOverlay'; import SpinnerOverlay from '@/components/elements/SpinnerOverlay';
import { ApiKey } from '@/api/account/getApiKeys';
interface Values { interface Values {
description: string; description: string;
allowedIps: string; allowedIps: string;
} }
export default () => { 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 { addError, clearFlashes } = useStoreActions((actions: Actions<ApplicationStore>) => actions.flashes);
const submit = (values: Values, { setSubmitting, resetForm }: FormikHelpers<Values>) => { const submit = (values: Values, { setSubmitting, resetForm }: FormikHelpers<Values>) => {
clearFlashes('account'); clearFlashes('account');
createApiKey(values.description, values.allowedIps) createApiKey(values.description, values.allowedIps)
.then(key => { .then(({ secretToken, ...key }) => {
resetForm(); resetForm();
setSubmitting(false); setSubmitting(false);
setApiKey(`${key.identifier}.${key.secretToken}`); setApiKey(`${key.identifier}${secretToken}`);
onKeyCreated(key);
}) })
.catch(error => { .catch(error => {
console.error(error); console.error(error);

View file

@ -0,0 +1,32 @@
import React from 'react';
import Modal from '@/components/elements/Modal';
interface Props {
title: string;
buttonText: string;
children: string;
visible: boolean;
onConfirmed: () => void;
onCanceled: () => void;
}
const ConfirmationModal = ({ title, children, visible, buttonText, onConfirmed, onCanceled }: Props) => (
<Modal
appear={true}
visible={visible}
onDismissed={() => onCanceled()}
>
<h3 className={'mb-6'}>{title}</h3>
<p className={'text-sm'}>{children}</p>
<div className={'flex items-center justify-end mt-8'}>
<button className={'btn btn-secondary btn-sm'} onClick={() => onCanceled()}>
Cancel
</button>
<button className={'btn btn-red btn-sm ml-4'} onClick={() => onConfirmed()}>
{buttonText}
</button>
</div>
</Modal>
);
export default ConfirmationModal;

View file

@ -25,7 +25,7 @@ Route::group(['prefix' => '/account'], function () {
Route::get('/api-keys', 'ApiKeyController@index'); Route::get('/api-keys', 'ApiKeyController@index');
Route::post('/api-keys', 'ApiKeyController@store'); Route::post('/api-keys', 'ApiKeyController@store');
Route::delete('/api-keys/{key}', 'ApiKeyController@delete'); Route::delete('/api-keys/{identifier}', 'ApiKeyController@delete');
}); });
/* /*