Add support for changing the server default allocation as a normal user

This commit is contained in:
Dane Everitt 2017-10-20 21:32:57 -05:00
parent 5a3428f0a0
commit d50ea18598
No known key found for this signature in database
GPG Key ID: EEA66103B3D71F53
14 changed files with 308 additions and 68 deletions

View File

@ -13,6 +13,7 @@ This project follows [Semantic Versioning](http://semver.org) guidelines.
* Ability to delete users and locations via the CLI.
* You can now require 2FA for all users, admins only, or at will using a simple configuration in the Admin CP.
* Added ability to export and import service options and their associated settings and environment variables via the Admin CP.
* Default allocation for a server can be changed on the front-end by users. This includes two new subuser permissions as well.
### Changed
* Theme colors and login pages updated to give a more unique feel to the project.

View File

@ -0,0 +1,9 @@
<?php
namespace Pterodactyl\Exceptions\Service\Allocation;
use Pterodactyl\Exceptions\PterodactylException;
class AllocationDoesNotBelongToServerException extends PterodactylException
{
}

View File

@ -41,11 +41,14 @@ class DatabaseController extends Controller
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\View\View
*
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
public function index(Request $request): View
{
$server = $request->attributes->get('server');
$this->injectJavascript();
$this->authorize('view-databases', $server);
$this->setRequest($request)->injectJavascript();
return view('server.databases.index', [
'databases' => $this->repository->getDatabasesForServer($server->id),
@ -58,11 +61,14 @@ class DatabaseController extends Controller
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\JsonResponse
*
* @throws \Illuminate\Auth\Access\AuthorizationException
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
*/
public function update(Request $request): JsonResponse
{
$this->authorize('reset-db-password', $request->attributes->get('server'));
$password = str_random(20);
$this->passwordService->handle($request->attributes->get('database'), $password);

View File

@ -86,28 +86,6 @@ class ServerController extends Controller
]);
}
/**
* Returns the database overview for a server.
*
* @param \Illuminate\Http\Request $request
* @param string $uuid
* @return \Illuminate\View\View
*/
public function getDatabases(Request $request, $uuid)
{
$server = Models\Server::byUuid($uuid);
$this->authorize('view-databases', $server);
$server->load('node', 'databases.host');
$server->js();
return view('server.settings.databases', [
'server' => $server,
'node' => $server->node,
'databases' => $server->databases,
]);
}
/**
* Returns the SFTP overview for a server.
*

View File

@ -0,0 +1,97 @@
<?php
namespace Pterodactyl\Http\Controllers\Server\Settings;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Http\JsonResponse;
use Pterodactyl\Http\Controllers\Controller;
use Pterodactyl\Contracts\Extensions\HashidsInterface;
use Pterodactyl\Traits\Controllers\JavascriptInjection;
use Pterodactyl\Services\Allocations\SetDefaultAllocationService;
use Pterodactyl\Contracts\Repository\AllocationRepositoryInterface;
use Pterodactyl\Exceptions\Service\Allocation\AllocationDoesNotBelongToServerException;
class AllocationController extends Controller
{
use JavascriptInjection;
/**
* @var \Pterodactyl\Services\Allocations\SetDefaultAllocationService
*/
private $defaultAllocationService;
/**
* @var \Pterodactyl\Contracts\Extensions\HashidsInterface
*/
private $hashids;
/**
* @var \Pterodactyl\Contracts\Repository\AllocationRepositoryInterface
*/
private $repository;
/**
* AllocationController constructor.
*
* @param \Pterodactyl\Contracts\Repository\AllocationRepositoryInterface $repository
* @param \Pterodactyl\Contracts\Extensions\HashidsInterface $hashids
* @param \Pterodactyl\Services\Allocations\SetDefaultAllocationService $defaultAllocationService
*/
public function __construct(
AllocationRepositoryInterface $repository,
HashidsInterface $hashids,
SetDefaultAllocationService $defaultAllocationService
) {
$this->defaultAllocationService = $defaultAllocationService;
$this->hashids = $hashids;
$this->repository = $repository;
}
/**
* Render the allocation management overview page for a server.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\View\View
*
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
public function index(Request $request): View
{
$server = $request->attributes->get('server');
$this->authorize('view-allocations', $server);
$this->setRequest($request)->injectJavascript();
return view('server.settings.allocation', [
'allocations' => $this->repository->findWhere([['server_id', '=', $server->id]]),
]);
}
/**
* Update the default allocation for a server.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\JsonResponse
*
* @throws \Illuminate\Auth\Access\AuthorizationException
* @throws \Pterodactyl\Exceptions\Http\Connection\DaemonConnectionException
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
*/
public function update(Request $request): JsonResponse
{
$server = $request->attributes->get('server');
$this->authorize('edit-allocation', $server);
$allocation = $this->hashids->decodeFirst($request->input('allocation'), 0);
try {
$this->defaultAllocationService->handle($server->id, $allocation);
} catch (AllocationDoesNotBelongToServerException $exception) {
return response()->json(['error' => 'No matching allocation was located for this server.'], 404);
}
return response()->json();
}
}

View File

@ -64,6 +64,16 @@ class Allocation extends Model implements CleansAttributes, ValidableContract
'server_id' => 'nullable|exists:servers,id',
];
/**
* Return a hashid encoded string to represent the ID of the allocation.
*
* @return string
*/
public function getHashidAttribute()
{
return app()->make('hashids')->encode($this->id);
}
/**
* Accessor to automatically provide the IP alias if defined.
*

View File

@ -86,7 +86,8 @@ class Permission extends Model implements CleansAttributes, ValidableContract
'delete-subuser' => null,
],
'server' => [
'set-connection' => null,
'view-allocations' => null,
'edit-allocation' => null,
'view-startup' => null,
'edit-startup' => null,
],

View File

@ -0,0 +1,110 @@
<?php
namespace Pterodactyl\Services\Allocations;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\Allocation;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Database\ConnectionInterface;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
use Pterodactyl\Contracts\Repository\AllocationRepositoryInterface;
use Pterodactyl\Exceptions\Http\Connection\DaemonConnectionException;
use Pterodactyl\Exceptions\Service\Allocation\AllocationDoesNotBelongToServerException;
use Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface as DaemonRepositoryInterface;
class SetDefaultAllocationService
{
/**
* @var \Illuminate\Database\ConnectionInterface
*/
private $connection;
/**
* @var \Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface
*/
private $daemonRepository;
/**
* @var \Pterodactyl\Contracts\Repository\AllocationRepositoryInterface
*/
private $repository;
/**
* @var \Pterodactyl\Contracts\Repository\ServerRepositoryInterface
*/
private $serverRepository;
/**
* SetDefaultAllocationService constructor.
*
* @param \Pterodactyl\Contracts\Repository\AllocationRepositoryInterface $repository
* @param \Illuminate\Database\ConnectionInterface $connection
* @param \Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface $daemonRepository
* @param \Pterodactyl\Contracts\Repository\ServerRepositoryInterface $serverRepository
*/
public function __construct(
AllocationRepositoryInterface $repository,
ConnectionInterface $connection,
DaemonRepositoryInterface $daemonRepository,
ServerRepositoryInterface $serverRepository
) {
$this->connection = $connection;
$this->daemonRepository = $daemonRepository;
$this->repository = $repository;
$this->serverRepository = $serverRepository;
}
/**
* Update the default allocation for a server only if that allocation is currently
* assigned to the specified server.
*
* @param int|\Pterodactyl\Models\Server $server
* @param int $allocation
* @return \Pterodactyl\Models\Allocation
*
* @throws \Pterodactyl\Exceptions\Http\Connection\DaemonConnectionException
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
* @throws \Pterodactyl\Exceptions\Service\Allocation\AllocationDoesNotBelongToServerException
*/
public function handle($server, int $allocation): Allocation
{
if (! $server instanceof Server) {
$server = $this->serverRepository->find($server);
}
$allocations = $this->repository->findWhere([['server_id', '=', $server->id]]);
$model = $allocations->filter(function ($model) use ($allocation) {
return $model->id === $allocation;
})->first();
if (! $model instanceof Allocation) {
throw new AllocationDoesNotBelongToServerException;
}
$this->connection->beginTransaction();
$this->serverRepository->withoutFresh()->update($server->id, ['allocation_id' => $model->id]);
// Update on the daemon.
try {
$this->daemonRepository->setAccessServer($server->uuid)->setNode($server->node_id)->update([
'build' => [
'default' => [
'ip' => $model->ip,
'port' => $model->port,
],
'ports|overwrite' => $allocations->groupBy('ip')->map(function ($item) {
return $item->pluck('port');
})->toArray(),
],
]);
$this->connection->commit();
} catch (RequestException $exception) {
$this->connection->rollBack();
throw new DaemonConnectionException($exception);
}
return $model;
}
}

View File

@ -14,17 +14,34 @@ use Illuminate\Http\Request;
trait JavascriptInjection
{
/**
* @var \Illuminate\Http\Request
*/
private $request;
/**
* Set the request object to use when injecting JS.
*
* @param \Illuminate\Http\Request $request
* @return $this
*/
public function setRequest(Request $request)
{
$this->request = $request;
return $this;
}
/**
* Injects server javascript into the page to be used by other services.
*
* @param array $args
* @param bool $overwrite
* @param \Illuminate\Http\Request|null $request
* @param array $args
* @param bool $overwrite
* @return array
*/
public function injectJavascript($args = [], $overwrite = false, Request $request = null)
public function injectJavascript($args = [], $overwrite = false)
{
$request = $request ?? app()->make(Request::class);
$request = $this->request ?? app()->make(Request::class);
$server = $request->attributes->get('server');
$token = $request->attributes->get('server_token');

View File

@ -20,7 +20,7 @@ return [
'subusers' => 'Subusers',
'schedules' => 'Schedules',
'configuration' => 'Configuration',
'port_allocations' => 'Port Allocations',
'port_allocations' => 'Allocation Settings',
'sftp_settings' => 'SFTP Settings',
'startup_parameters' => 'Startup Parameters',
'databases' => 'Databases',

View File

@ -189,9 +189,13 @@ return [
'title' => 'Delete Subuser',
'description' => 'Allows a user to delete other subusers on the server.',
],
'set_connection' => [
'title' => 'Set Default Connection',
'description' => 'Allows user to set the default connection used for a server as well as view avaliable ports.',
'view_allocations' => [
'title' => 'View Allocations',
'description' => 'Allows user to view all of the IPs and ports assigned to a server.',
],
'edit_allocation' => [
'title' => 'Edit Default Connection',
'description' => 'Allows user to change the default connection allocation to use for a server.',
],
'view_startup' => [
'title' => 'View Startup Command',

View File

@ -166,7 +166,7 @@
</a>
</li>
@endcan
@if(Gate::allows('view-startup', $server) || Gate::allows('view-sftp', $server) || Gate::allows('view-databases', $server) || Gate::allows('view-allocation', $server))
@if(Gate::allows('view-startup', $server) || Gate::allows('view-sftp', $server) || Gate::allows('view-allocation', $server))
<li class="treeview
@if(starts_with(Route::currentRouteName(), 'server.settings'))
active

View File

@ -35,7 +35,7 @@
<th>@lang('strings.port')</th>
<th></th>
</tr>
@foreach ($server->allocations as $allocation)
@foreach ($allocations as $allocation)
<tr>
<td>
<code>{{ $allocation->ip }}</code>
@ -50,9 +50,9 @@
<td><code>{{ $allocation->port }}</code></td>
<td class="col-xs-2 middle">
@if($allocation->id === $server->allocation_id)
<span class="label label-success" data-allocation="{{ $allocation->id }}">@lang('strings.primary')</span>
<a class="btn btn-xs btn-success disabled" data-action="set-default" data-allocation="{{ $allocation->hashid }}" role="button">@lang('strings.primary')</a>
@else
<span class="label label-default" data-action="set-connection" data-allocation="{{ $allocation->id }}">@lang('strings.make_primary')</span>
<a class="btn btn-xs btn-default" data-action="set-default" data-allocation="{{ $allocation->hashid }}" role="button">@lang('strings.make_primary')</a>
@endif
</td>
</tr>
@ -60,6 +60,9 @@
</tbody>
</table>
</div>
<div id="toggleActivityOverlay" class="overlay hidden">
<i class="fa fa-refresh fa-spin"></i>
</div>
</div>
</div>
<div class="col-sm-4">
@ -79,37 +82,39 @@
@parent
{!! Theme::js('js/frontend/server.socket.js') !!}
<script>
@can('reset-db-password', $server)
$('[data-action="reset-database-password"]').click(function (e) {
e.preventDefault();
var block = $(this);
$(this).find('i').addClass('fa-spin');
$.ajax({
type: 'POST',
url: Router.route('server.ajax.reset-database-password', { server: Pterodactyl.server.uuidShort }),
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content'),
},
data: {
'database': $(this).data('id')
}
}).done(function (data) {
block.parent().find('code').html(data);
}).fail(function(jqXHR, textStatus, errorThrown) {
console.error(jqXHR);
var error = 'An error occured while trying to process this request.';
if (typeof jqXHR.responseJSON !== 'undefined' && typeof jqXHR.responseJSON.error !== 'undefined') {
error = jqXHR.responseJSON.error;
}
swal({
type: 'error',
title: 'Whoops!',
text: error
$(document).ready(function () {
@can('edit-allocation', $server)
(function triggerClickHandler() {
$('a[data-action="set-default"]:not(.disabled)').click(function (e) {
$('#toggleActivityOverlay').removeClass('hidden');
e.preventDefault();
var self = $(this);
$.ajax({
type: 'PATCH',
url: Router.route('server.settings.allocation', { server: Pterodactyl.server.uuidShort }),
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content'),
},
data: {
'allocation': $(this).data('allocation')
}
}).done(function () {
self.parents().eq(2).find('a[role="button"]').removeClass('btn-success disabled').addClass('btn-default').html('{{ trans('strings.make_primary') }}');
self.removeClass('btn-default').addClass('btn-success disabled').html('{{ trans('strings.primary') }}');
}).fail(function(jqXHR) {
console.error(jqXHR);
var error = 'An error occured while trying to process this request.';
if (typeof jqXHR.responseJSON !== 'undefined' && typeof jqXHR.responseJSON.error !== 'undefined') {
error = jqXHR.responseJSON.error;
}
swal({type: 'error', title: 'Whoops!', text: error});
}).always(function () {
triggerClickHandler();
$('#toggleActivityOverlay').addClass('hidden');
})
});
}).always(function () {
block.find('i').removeClass('fa-spin');
});
})();
@endcan
});
@endcan
</script>
@endsection

View File

@ -18,9 +18,11 @@ Route::get('/console', 'ConsoleController@console')->name('server.console');
|
*/
Route::group(['prefix' => 'settings'], function () {
Route::get('/allocation', 'Settings\AllocationController@index')->name('server.settings.allocation');
Route::patch('/allocation', 'Settings\AllocationController@update');
Route::get('/sftp', 'ServerController@getSFTP')->name('server.settings.sftp');
Route::get('/startup', 'ServerController@getStartup')->name('server.settings.startup');
Route::get('/allocation', 'ServerController@getAllocation')->name('server.settings.allocation');
Route::post('/sftp', 'ServerController@postSettingsSFTP');
Route::post('/startup', 'ServerController@postSettingsStartup');