Support deleting a task from a schedule

This commit is contained in:
Dane Everitt 2020-03-18 21:08:32 -07:00
parent 5345a2a3e1
commit 78ed343a34
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
10 changed files with 172 additions and 8 deletions

View file

@ -0,0 +1,20 @@
<?php
namespace Pterodactyl\Exceptions\Http;
use Illuminate\Http\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
class HttpForbiddenException extends HttpException
{
/**
* HttpForbiddenException constructor.
*
* @param string|null $message
* @param \Throwable|null $previous
*/
public function __construct(string $message = null, \Throwable $previous = null)
{
parent::__construct(Response::HTTP_FORBIDDEN, $message, $previous);
}
}

View file

@ -0,0 +1,59 @@
<?php
namespace Pterodactyl\Http\Controllers\Api\Client\Servers;
use Pterodactyl\Models\Task;
use Illuminate\Http\Response;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\Schedule;
use Illuminate\Http\JsonResponse;
use Pterodactyl\Models\Permission;
use Pterodactyl\Repositories\Eloquent\TaskRepository;
use Pterodactyl\Exceptions\Http\HttpForbiddenException;
use Pterodactyl\Http\Requests\Api\Client\ClientApiRequest;
use Pterodactyl\Http\Controllers\Api\Client\ClientApiController;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class ScheduleTaskController extends ClientApiController
{
/**
* @var \Pterodactyl\Repositories\Eloquent\TaskRepository
*/
private $repository;
/**
* ScheduleTaskController constructor.
*
* @param \Pterodactyl\Repositories\Eloquent\TaskRepository $repository
*/
public function __construct(TaskRepository $repository)
{
parent::__construct();
$this->repository = $repository;
}
/**
* Determines if a user can delete the task for a given server.
*
* @param \Pterodactyl\Http\Requests\Api\Client\ClientApiRequest $request
* @param \Pterodactyl\Models\Server $server
* @param \Pterodactyl\Models\Schedule $schedule
* @param \Pterodactyl\Models\Task $task
* @return \Illuminate\Http\JsonResponse
*/
public function delete(ClientApiRequest $request, Server $server, Schedule $schedule, Task $task)
{
if ($task->schedule_id !== $schedule->id || $schedule->server_id !== $server->id) {
throw new NotFoundHttpException;
}
if (! $request->user()->can(Permission::ACTION_SCHEDULE_UPDATE, $server)) {
throw new HttpForbiddenException('You do not have permission to perform this action.');
}
$this->repository->delete($task->id);
return JsonResponse::create(null, Response::HTTP_NO_CONTENT);
}
}

View file

@ -8,9 +8,9 @@ use Pterodactyl\Contracts\Http\ClientPermissionsRequest;
use Pterodactyl\Http\Requests\Api\Application\ApplicationApiRequest;
/**
* @method User user($guard = null)
* @method \Pterodactyl\Models\User user($guard = null)
*/
abstract class ClientApiRequest extends ApplicationApiRequest
class ClientApiRequest extends ApplicationApiRequest
{
/**
* Determine if the current user is authorized to perform the requested action against the API.

View file

@ -12,6 +12,14 @@ class Permission extends Validable
*/
const RESOURCE_NAME = 'subuser_permission';
/**
* Constants defining different permissions available.
*/
const ACTION_SCHEDULE_READ = 'schedule.read';
const ACTION_SCHEDULE_CREATE = 'schedule.create';
const ACTION_SCHEDULE_UPDATE = 'schedule.update';
const ACTION_SCHEDULE_DELETE = 'schedule.delete';
/**
* Should timestamps be used on this model.
*

View file

@ -0,0 +1,9 @@
import http from '@/api/http';
export default (uuid: string, scheduleId: number, taskId: number): Promise<void> => {
return new Promise((resolve, reject) => {
http.delete(`/api/client/servers/${uuid}/schedules/${scheduleId}/tasks/${taskId}`)
.then(() => resolve())
.catch(reject);
})
};

View file

@ -13,11 +13,11 @@ interface Props {
const SpinnerOverlay = ({ size, fixed, visible, backgroundOpacity }: Props) => (
<CSSTransition timeout={150} classNames={'fade'} in={visible} unmountOnExit={true}>
<div
className={classNames('z-50 pin-t pin-l flex items-center justify-center w-full h-full rounded', {
className={classNames('pin-t pin-l flex items-center justify-center w-full h-full rounded', {
absolute: !fixed,
fixed: fixed,
})}
style={{ background: `rgba(0, 0, 0, ${backgroundOpacity || 0.45})` }}
style={{ zIndex: 9999, background: `rgba(0, 0, 0, ${backgroundOpacity || 0.45})` }}
>
<Spinner size={size}/>
</div>

View file

@ -0,0 +1,26 @@
import React from 'react';
import Modal, { RequiredModalProps } from '@/components/elements/Modal';
type Props = RequiredModalProps & {
onConfirmed: () => void;
}
export default ({ onConfirmed, ...props }: Props) => (
<Modal {...props}>
<h2>Confirm task deletion</h2>
<p className={'text-sm mt-4'}>
Are you sure you want to delete this task? This action cannot be undone.
</p>
<div className={'flex items-center justify-end mt-8'}>
<button className={'btn btn-secondary btn-sm'} onClick={() => props.onDismissed()}>
Cancel
</button>
<button className={'btn btn-red btn-sm ml-4'} onClick={() => {
props.onDismissed();
onConfirmed();
}}>
Delete Task
</button>
</div>
</Modal>
);

View file

@ -79,7 +79,14 @@ export default ({ match, location: { state } }: RouteComponentProps<Params, {},
key={task.id}
className={'bg-neutral-700 border border-neutral-600 mb-2 px-6 py-4 rounded'}
>
<ScheduleTaskRow task={task}/>
<ScheduleTaskRow
task={task}
schedule={schedule.id}
onTaskRemoved={() => setSchedule(s => ({
...s!,
tasks: s!.tasks.filter(t => t.id !== task.id),
}))}
/>
</div>
))
}

View file

@ -1,17 +1,49 @@
import React from 'react';
import { Task } from '@/api/server/schedules/getServerSchedules';
import React, { useState } from 'react';
import { Schedule, Task } from '@/api/server/schedules/getServerSchedules';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faTrashAlt } from '@fortawesome/free-solid-svg-icons/faTrashAlt';
import { faCode } from '@fortawesome/free-solid-svg-icons/faCode';
import { faToggleOn } from '@fortawesome/free-solid-svg-icons/faToggleOn';
import ConfirmTaskDeletionModal from '@/components/server/schedules/ConfirmTaskDeletionModal';
import { ServerContext } from '@/state/server';
import { Actions, useStoreActions } from 'easy-peasy';
import { ApplicationStore } from '@/state';
import deleteScheduleTask from '@/api/server/schedules/deleteScheduleTask';
import { httpErrorToHuman } from '@/api/http';
import SpinnerOverlay from '@/components/elements/SpinnerOverlay';
interface Props {
schedule: number;
task: Task;
onTaskRemoved: () => void;
}
export default ({ task }: Props) => {
export default ({ schedule, task, onTaskRemoved }: Props) => {
const [visible, setVisible] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const uuid = ServerContext.useStoreState(state => state.server.data!.uuid);
const { clearFlashes, addError } = useStoreActions((actions: Actions<ApplicationStore>) => actions.flashes);
const onConfirmDeletion = () => {
setIsLoading(true);
clearFlashes('schedules');
deleteScheduleTask(uuid, schedule, task.id)
.then(() => onTaskRemoved())
.catch(error => {
console.error(error);
setIsLoading(false);
addError({ message: httpErrorToHuman(error), key: 'schedules' });
});
};
return (
<div className={'flex items-center'}>
<SpinnerOverlay visible={isLoading} fixed={true} size={'large'}/>
<ConfirmTaskDeletionModal
visible={visible}
onDismissed={() => setVisible(false)}
onConfirmed={() => onConfirmDeletion()}
/>
<FontAwesomeIcon icon={task.action === 'command' ? faCode : faToggleOn} className={'text-lg text-white'}/>
<div className={'flex-1'}>
<p className={'ml-6 text-neutral-300 mb-2 uppercase text-xs'}>
@ -34,7 +66,9 @@ export default ({ task }: Props) => {
<div>
<a
href={'#'}
aria-label={'Delete scheduled task'}
className={'text-sm p-2 text-neutral-500 hover:text-red-600 transition-color duration-150'}
onClick={() => setVisible(true)}
>
<FontAwesomeIcon icon={faTrashAlt}/>
</a>

View file

@ -62,6 +62,7 @@ Route::group(['prefix' => '/servers/{server}', 'middleware' => [AuthenticateServ
Route::group(['prefix' => '/schedules'], function () {
Route::get('/', 'Servers\ScheduleController@index');
Route::get('/{schedule}', 'Servers\ScheduleController@view');
Route::delete('/{schedule}/tasks/{task}', 'Servers\ScheduleTaskController@delete');
});
Route::group(['prefix' => '/network'], function () {