Add base support for creating a new API key for an account

This commit is contained in:
Dane Everitt 2020-03-22 18:15:38 -07:00
parent 32f25170f1
commit 933a4733e8
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
17 changed files with 371 additions and 13 deletions

View file

@ -0,0 +1,86 @@
<?php
namespace Pterodactyl\Http\Controllers\Api\Client;
use Pterodactyl\Models\ApiKey;
use Pterodactyl\Exceptions\DisplayException;
use Illuminate\Contracts\Encryption\Encrypter;
use Pterodactyl\Services\Api\KeyCreationService;
use Pterodactyl\Http\Requests\Api\Client\ClientApiRequest;
use Pterodactyl\Transformers\Api\Client\ApiKeyTransformer;
use Pterodactyl\Http\Requests\Api\Client\Account\StoreApiKeyRequest;
class ApiKeyController extends ClientApiController
{
/**
* @var \Pterodactyl\Services\Api\KeyCreationService
*/
private $keyCreationService;
/**
* @var \Illuminate\Contracts\Encryption\Encrypter
*/
private $encrypter;
/**
* ApiKeyController constructor.
*
* @param \Illuminate\Contracts\Encryption\Encrypter $encrypter
* @param \Pterodactyl\Services\Api\KeyCreationService $keyCreationService
*/
public function __construct(Encrypter $encrypter, KeyCreationService $keyCreationService)
{
parent::__construct();
$this->encrypter = $encrypter;
$this->keyCreationService = $keyCreationService;
}
/**
* Returns all of the API keys that exist for the given client.
*
* @param \Pterodactyl\Http\Requests\Api\Client\ClientApiRequest $request
* @return array
*/
public function index(ClientApiRequest $request)
{
return $this->fractal->collection($request->user()->apiKeys)
->transformWith($this->getTransformer(ApiKeyTransformer::class))
->toArray();
}
/**
* Store a new API key for a user's account.
*
* @param \Pterodactyl\Http\Requests\Api\Client\Account\StoreApiKeyRequest $request
* @return array
*
* @throws \Pterodactyl\Exceptions\DisplayException
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
*/
public function store(StoreApiKeyRequest $request)
{
if ($request->user()->apiKeys->count() >= 5) {
throw new DisplayException(
'You have reached the account limit for number of API keys.'
);
}
$key = $this->keyCreationService->setKeyType(ApiKey::TYPE_ACCOUNT)->handle([
'user_id' => $request->user()->id,
'memo' => $request->input('description'),
'allowed_ips' => $request->input('allowed_ips') ?? [],
]);
return $this->fractal->item($key)
->transformWith($this->getTransformer(ApiKeyTransformer::class))
->addMeta([
'secret_token' => $this->encrypter->decrypt($key->token),
])
->toArray();
}
public function delete()
{
}
}

View file

@ -0,0 +1,20 @@
<?php
namespace Pterodactyl\Http\Requests\Api\Client\Account;
use Pterodactyl\Http\Requests\Api\Client\ClientApiRequest;
class StoreApiKeyRequest extends ClientApiRequest
{
/**
* @return array
*/
public function rules(): array
{
return [
'description' => 'required|string|min:4',
'allowed_ips' => 'array',
'allowed_ips.*' => 'ip',
];
}
}

View file

@ -4,8 +4,22 @@ namespace Pterodactyl\Models;
use Pterodactyl\Services\Acl\Api\AdminAcl; use Pterodactyl\Services\Acl\Api\AdminAcl;
/**
* @property int $id
* @property int $user_id
* @property int $key_type
* @property string $identifier
* @property string $token
* @property array $allowed_ips
* @property string $memo
* @property \Carbon\Carbon|null $last_used_at
* @property \Carbon\Carbon $created_at
* @property \Carbon\Carbon $updated_at
*/
class ApiKey extends Validable class ApiKey extends Validable
{ {
const RESOURCE_NAME = 'api_key';
/** /**
* Different API keys that can exist on the system. * Different API keys that can exist on the system.
*/ */

View file

@ -36,6 +36,7 @@ use Pterodactyl\Notifications\SendPasswordReset as ResetPasswordNotification;
* @property \Carbon\Carbon $updated_at * @property \Carbon\Carbon $updated_at
* *
* @property string $name * @property string $name
* @property \Pterodactyl\Models\ApiKey[]|\Illuminate\Database\Eloquent\Collection $apiKeys
* @property \Pterodactyl\Models\Permission[]|\Illuminate\Database\Eloquent\Collection $permissions * @property \Pterodactyl\Models\Permission[]|\Illuminate\Database\Eloquent\Collection $permissions
* @property \Pterodactyl\Models\Server[]|\Illuminate\Database\Eloquent\Collection $servers * @property \Pterodactyl\Models\Server[]|\Illuminate\Database\Eloquent\Collection $servers
* @property \Pterodactyl\Models\Subuser[]|\Illuminate\Database\Eloquent\Collection $subuserOf * @property \Pterodactyl\Models\Subuser[]|\Illuminate\Database\Eloquent\Collection $subuserOf
@ -258,4 +259,13 @@ class User extends Validable implements
{ {
return $this->hasMany(DaemonKey::class); return $this->hasMany(DaemonKey::class);
} }
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function apiKeys()
{
return $this->hasMany(ApiKey::class)
->where('key_type', ApiKey::TYPE_ACCOUNT);
}
} }

View file

@ -72,8 +72,6 @@ class KeyCreationService
$data = array_merge($data, $permissions); $data = array_merge($data, $permissions);
} }
$instance = $this->repository->create($data, true, true); return $this->repository->create($data, true, true);
return $instance;
} }
} }

View file

@ -0,0 +1,33 @@
<?php
namespace Pterodactyl\Transformers\Api\Client;
use Pterodactyl\Models\ApiKey;
class ApiKeyTransformer extends BaseClientTransformer
{
/**
* {@inheritdoc}
*/
public function getResourceName(): string
{
return ApiKey::RESOURCE_NAME;
}
/**
* Transform this model into a representation that can be consumed by a client.
*
* @param \Pterodactyl\Models\ApiKey $model
* @return array
*/
public function transform(ApiKey $model)
{
return [
'identifier' => $model->identifier,
'description' => $model->memo,
'allowed_ips' => $model->allowed_ips,
'last_used_at' => $model->last_used_at ? $model->last_used_at->toIso8601String() : null,
'created_at' => $model->created_at->toIso8601String(),
];
}
}

View file

@ -43,6 +43,7 @@
"devDependencies": { "devDependencies": {
"@babel/core": "^7.7.5", "@babel/core": "^7.7.5",
"@babel/plugin-proposal-class-properties": "^7.7.4", "@babel/plugin-proposal-class-properties": "^7.7.4",
"@babel/plugin-proposal-nullish-coalescing-operator": "^7.8.3",
"@babel/plugin-proposal-object-rest-spread": "^7.7.4", "@babel/plugin-proposal-object-rest-spread": "^7.7.4",
"@babel/plugin-proposal-optional-chaining": "^7.8.3", "@babel/plugin-proposal-optional-chaining": "^7.8.3",
"@babel/plugin-syntax-dynamic-import": "^7.7.4", "@babel/plugin-syntax-dynamic-import": "^7.7.4",

View file

@ -0,0 +1,17 @@
import http from '@/api/http';
import { ApiKey, rawDataToApiKey } from '@/api/account/getApiKeys';
export default (description: string, allowedIps: string): Promise<ApiKey & { secretToken: string }> => {
return new Promise((resolve, reject) => {
http.post(`/api/client/account/api-keys`, {
description,
// eslint-disable-next-line @typescript-eslint/camelcase
allowed_ips: allowedIps.length > 0 ? allowedIps.split('\n') : [],
})
.then(({ data }) => resolve({
...rawDataToApiKey(data.attributes),
secretToken: data.meta?.secret_token ?? '',
}))
.catch(reject);
});
};

View file

@ -0,0 +1,25 @@
import http from '@/api/http';
export interface ApiKey {
identifier: string;
description: string;
allowedIps: string[];
createdAt: Date | null;
lastUsedAt: Date | null;
}
export const rawDataToApiKey = (data: any): ApiKey => ({
identifier: data.identifier,
description: data.description,
allowedIps: data.allowed_ips,
createdAt: data.created_at ? new Date(data.created_at) : null,
lastUsedAt: data.last_used_at ? new Date(data.last_used_at) : null,
});
export default (): Promise<ApiKey[]> => {
return new Promise((resolve, reject) => {
http.get('/api/client/account/api-keys')
.then(({ data }) => resolve((data.data || []).map(rawDataToApiKey)))
.catch(reject);
});
};

View file

@ -0,0 +1,16 @@
import React from 'react';
import ContentBox from '@/components/elements/ContentBox';
import CreateApiKeyForm from '@/components/dashboard/forms/CreateApiKeyForm';
export default () => {
return (
<div className={'my-10 flex'}>
<ContentBox title={'Create API Key'} className={'flex-1'} showFlashes={'account'}>
<CreateApiKeyForm/>
</ContentBox>
<ContentBox title={'API Keys'} className={'ml-10 flex-1'}>
<p>Testing</p>
</ContentBox>
</div>
);
};

View file

@ -0,0 +1,106 @@
import React, { useState } from 'react';
import { Field, Form, Formik, FormikHelpers } from 'formik';
import { object, string } from 'yup';
import FormikFieldWrapper from '@/components/elements/FormikFieldWrapper';
import Modal from '@/components/elements/Modal';
import createApiKey from '@/api/account/createApiKey';
import { Actions, useStoreActions } from 'easy-peasy';
import { ApplicationStore } from '@/state';
import { httpErrorToHuman } from '@/api/http';
import SpinnerOverlay from '@/components/elements/SpinnerOverlay';
interface Values {
description: string;
allowedIps: string;
}
export default () => {
const [ apiKey, setApiKey ] = useState('');
const { addError, clearFlashes } = useStoreActions((actions: Actions<ApplicationStore>) => actions.flashes);
const submit = (values: Values, { setSubmitting, resetForm }: FormikHelpers<Values>) => {
clearFlashes('account');
createApiKey(values.description, values.allowedIps)
.then(key => {
resetForm();
setSubmitting(false);
setApiKey(`${key.identifier}.${key.secretToken}`);
})
.catch(error => {
console.error(error);
addError({ key: 'account', message: httpErrorToHuman(error) });
setSubmitting(false);
});
};
return (
<>
<Modal
visible={apiKey.length > 0}
onDismissed={() => setApiKey('')}
closeOnEscape={false}
closeOnBackground={false}
>
<h3 className={'mb-6'}>Your API Key</h3>
<p className={'text-sm mb-6'}>
The API key you have requested is shown below. Please store this in a safe location, it will not be
shown again.
</p>
<pre className={'text-sm bg-neutral-900 rounded py-2 px-4 font-mono'}>
<code className={'font-mono'}>{apiKey}</code>
</pre>
<div className={'flex justify-end mt-6'}>
<button
type={'button'}
className={'btn btn-secondary btn-sm'}
onClick={() => setApiKey('')}
>
Close
</button>
</div>
</Modal>
<Formik
onSubmit={submit}
initialValues={{
description: '',
allowedIps: '',
}}
validationSchema={object().shape({
allowedIps: string(),
description: string().required().min(4),
})}
>
{({ isSubmitting }) => (
<Form>
<SpinnerOverlay visible={isSubmitting}/>
<FormikFieldWrapper
label={'Description'}
name={'description'}
description={'A description of this API key.'}
className={'mb-6'}
>
<Field name={'description'} className={'input-dark'}/>
</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.'}
>
<Field
as={'textarea'}
name={'allowedIps'}
className={'input-dark h-32'}
/>
</FormikFieldWrapper>
<div className={'flex justify-end mt-6'}>
<button className={'btn btn-primary btn-sm'}>
Create
</button>
</div>
</Form>
)}
</Formik>
</>
);
};

View file

@ -4,6 +4,7 @@ import classNames from 'classnames';
import InputError from '@/components/elements/InputError'; import InputError from '@/components/elements/InputError';
interface Props { interface Props {
id?: string;
name: string; name: string;
children: React.ReactNode; children: React.ReactNode;
className?: string; className?: string;
@ -12,12 +13,12 @@ interface Props {
validate?: (value: any) => undefined | string | Promise<any>; validate?: (value: any) => undefined | string | Promise<any>;
} }
const FormikFieldWrapper = ({ name, label, className, description, validate, children }: Props) => ( const FormikFieldWrapper = ({ id, name, label, className, description, validate, children }: Props) => (
<Field name={name} validate={validate}> <Field name={name} validate={validate}>
{ {
({ field, form: { errors, touched } }: FieldProps) => ( ({ field, form: { errors, touched } }: FieldProps) => (
<div className={classNames(className, { 'has-error': touched[field.name] && errors[field.name] })}> <div className={classNames(className, { 'has-error': touched[field.name] && errors[field.name] })}>
{label && <label htmlFor={name}>{label}</label>} {label && <label htmlFor={id} className={'input-dark-label'}>{label}</label>}
{children} {children}
<InputError errors={errors} touched={touched} name={field.name}> <InputError errors={errors} touched={touched} name={field.name}>
{description ? <p className={'input-help'}>{description}</p> : null} {description ? <p className={'input-help'}>{description}</p> : null}

View file

@ -1,18 +1,28 @@
import * as React from 'react'; import * as React from 'react';
import { Route, RouteComponentProps, Switch } from 'react-router-dom'; import { NavLink, Route, RouteComponentProps, Switch } from 'react-router-dom';
import DesignElementsContainer from '@/components/dashboard/DesignElementsContainer'; import DesignElementsContainer from '@/components/dashboard/DesignElementsContainer';
import AccountOverviewContainer from '@/components/dashboard/AccountOverviewContainer'; import AccountOverviewContainer from '@/components/dashboard/AccountOverviewContainer';
import NavigationBar from '@/components/NavigationBar'; import NavigationBar from '@/components/NavigationBar';
import DashboardContainer from '@/components/dashboard/DashboardContainer'; import DashboardContainer from '@/components/dashboard/DashboardContainer';
import TransitionRouter from '@/TransitionRouter'; import TransitionRouter from '@/TransitionRouter';
import AccountApiContainer from '@/components/dashboard/AccountApiContainer';
export default ({ location }: RouteComponentProps) => ( export default ({ location }: RouteComponentProps) => (
<React.Fragment> <React.Fragment>
<NavigationBar/> <NavigationBar/>
{location.pathname.startsWith('/account') &&
<div id={'sub-navigation'}>
<div className={'items'}>
<NavLink to={`/account`} exact>Settings</NavLink>
<NavLink to={`/account/api`}>API Credentials</NavLink>
</div>
</div>
}
<TransitionRouter> <TransitionRouter>
<Switch location={location}> <Switch location={location}>
<Route path={'/'} component={DashboardContainer} exact/> <Route path={'/'} component={DashboardContainer} exact/>
<Route path={'/account'} component={AccountOverviewContainer}/> <Route path={'/account'} component={AccountOverviewContainer} exact/>
<Route path={'/account/api'} component={AccountApiContainer} exact/>
<Route path={'/design'} component={DesignElementsContainer}/> <Route path={'/design'} component={DesignElementsContainer}/>
</Switch> </Switch>
</TransitionRouter> </TransitionRouter>

View file

@ -65,12 +65,8 @@ input[type=number] {
@apply .text-xs .text-neutral-400; @apply .text-xs .text-neutral-400;
} }
&.error {
@apply .text-red-100 .border-red-400;
}
&.error + .input-help { &.error + .input-help {
@apply .text-red-400; @apply .text-red-400 !important;
} }
&:disabled { &:disabled {
@ -78,11 +74,15 @@ input[type=number] {
} }
} }
.has-error .input-dark:not(select), .input-dark.error {
@apply .text-red-100 .border-red-400;
}
.input-help { .input-help {
@apply .text-xs .text-neutral-400 .pt-2; @apply .text-xs .text-neutral-400 .pt-2;
&.error { &.error {
@apply .text-red-400; @apply .text-red-400 !important;
} }
} }

View file

@ -22,6 +22,10 @@ Route::group(['prefix' => '/account'], function () {
Route::put('/email', 'AccountController@updateEmail')->name('api.client.account.update-email'); Route::put('/email', 'AccountController@updateEmail')->name('api.client.account.update-email');
Route::put('/password', 'AccountController@updatePassword')->name('api.client.account.update-password'); Route::put('/password', 'AccountController@updatePassword')->name('api.client.account.update-password');
Route::get('/api-keys', 'ApiKeyController@index');
Route::post('/api-keys', 'ApiKeyController@store');
Route::delete('/api-keys/{key}', 'ApiKeyController@delete');
}); });
/* /*

View file

@ -87,6 +87,7 @@ module.exports = {
'@babel/proposal-class-properties', '@babel/proposal-class-properties',
'@babel/proposal-object-rest-spread', '@babel/proposal-object-rest-spread',
'@babel/proposal-optional-chaining', '@babel/proposal-optional-chaining',
'@babel/proposal-nullish-coalescing-operator',
'@babel/syntax-dynamic-import', '@babel/syntax-dynamic-import',
], ],
}, },
@ -164,6 +165,7 @@ module.exports = {
], ],
}, },
watchOptions: { watchOptions: {
poll: 1000,
ignored: /node_modules/, ignored: /node_modules/,
}, },
devServer: { devServer: {

View file

@ -250,6 +250,14 @@
"@babel/helper-plugin-utils" "^7.0.0" "@babel/helper-plugin-utils" "^7.0.0"
"@babel/plugin-syntax-json-strings" "^7.7.4" "@babel/plugin-syntax-json-strings" "^7.7.4"
"@babel/plugin-proposal-nullish-coalescing-operator@^7.8.3":
version "7.8.3"
resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-nullish-coalescing-operator/-/plugin-proposal-nullish-coalescing-operator-7.8.3.tgz#e4572253fdeed65cddeecfdab3f928afeb2fd5d2"
integrity sha512-TS9MlfzXpXKt6YYomudb/KU7nQI6/xnapG6in1uZxoxDghuSMZsPb6D2fyUwNYSAp4l1iR7QtFOjkqcRYcUsfw==
dependencies:
"@babel/helper-plugin-utils" "^7.8.3"
"@babel/plugin-syntax-nullish-coalescing-operator" "^7.8.0"
"@babel/plugin-proposal-object-rest-spread@^7.7.4": "@babel/plugin-proposal-object-rest-spread@^7.7.4":
version "7.7.4" version "7.7.4"
resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-object-rest-spread/-/plugin-proposal-object-rest-spread-7.7.4.tgz#cc57849894a5c774214178c8ab64f6334ec8af71" resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-object-rest-spread/-/plugin-proposal-object-rest-spread-7.7.4.tgz#cc57849894a5c774214178c8ab64f6334ec8af71"
@ -302,6 +310,13 @@
dependencies: dependencies:
"@babel/helper-plugin-utils" "^7.0.0" "@babel/helper-plugin-utils" "^7.0.0"
"@babel/plugin-syntax-nullish-coalescing-operator@^7.8.0":
version "7.8.3"
resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz#167ed70368886081f74b5c36c65a88c03b66d1a9"
integrity sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==
dependencies:
"@babel/helper-plugin-utils" "^7.8.0"
"@babel/plugin-syntax-object-rest-spread@^7.7.4": "@babel/plugin-syntax-object-rest-spread@^7.7.4":
version "7.7.4" version "7.7.4"
resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.7.4.tgz#47cf220d19d6d0d7b154304701f468fc1cc6ff46" resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.7.4.tgz#47cf220d19d6d0d7b154304701f468fc1cc6ff46"