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. * 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. * 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. * 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 ### Changed
* Theme colors and login pages updated to give a more unique feel to the project. * 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 * @param \Illuminate\Http\Request $request
* @return \Illuminate\View\View * @return \Illuminate\View\View
*
* @throws \Illuminate\Auth\Access\AuthorizationException
*/ */
public function index(Request $request): View public function index(Request $request): View
{ {
$server = $request->attributes->get('server'); $server = $request->attributes->get('server');
$this->injectJavascript(); $this->authorize('view-databases', $server);
$this->setRequest($request)->injectJavascript();
return view('server.databases.index', [ return view('server.databases.index', [
'databases' => $this->repository->getDatabasesForServer($server->id), 'databases' => $this->repository->getDatabasesForServer($server->id),
@ -58,11 +61,14 @@ class DatabaseController extends Controller
* @param \Illuminate\Http\Request $request * @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\JsonResponse * @return \Illuminate\Http\JsonResponse
* *
* @throws \Illuminate\Auth\Access\AuthorizationException
* @throws \Pterodactyl\Exceptions\Model\DataValidationException * @throws \Pterodactyl\Exceptions\Model\DataValidationException
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
*/ */
public function update(Request $request): JsonResponse public function update(Request $request): JsonResponse
{ {
$this->authorize('reset-db-password', $request->attributes->get('server'));
$password = str_random(20); $password = str_random(20);
$this->passwordService->handle($request->attributes->get('database'), $password); $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. * 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', '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. * 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, 'delete-subuser' => null,
], ],
'server' => [ 'server' => [
'set-connection' => null, 'view-allocations' => null,
'edit-allocation' => null,
'view-startup' => null, 'view-startup' => null,
'edit-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 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. * Injects server javascript into the page to be used by other services.
* *
* @param array $args * @param array $args
* @param bool $overwrite * @param bool $overwrite
* @param \Illuminate\Http\Request|null $request
* @return array * @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'); $server = $request->attributes->get('server');
$token = $request->attributes->get('server_token'); $token = $request->attributes->get('server_token');

View file

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

View file

@ -189,9 +189,13 @@ return [
'title' => 'Delete Subuser', 'title' => 'Delete Subuser',
'description' => 'Allows a user to delete other subusers on the server.', 'description' => 'Allows a user to delete other subusers on the server.',
], ],
'set_connection' => [ 'view_allocations' => [
'title' => 'Set Default Connection', 'title' => 'View Allocations',
'description' => 'Allows user to set the default connection used for a server as well as view avaliable ports.', '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' => [ 'view_startup' => [
'title' => 'View Startup Command', 'title' => 'View Startup Command',

View file

@ -166,7 +166,7 @@
</a> </a>
</li> </li>
@endcan @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 <li class="treeview
@if(starts_with(Route::currentRouteName(), 'server.settings')) @if(starts_with(Route::currentRouteName(), 'server.settings'))
active active

View file

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

View file

@ -18,9 +18,11 @@ Route::get('/console', 'ConsoleController@console')->name('server.console');
| |
*/ */
Route::group(['prefix' => 'settings'], function () { 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('/sftp', 'ServerController@getSFTP')->name('server.settings.sftp');
Route::get('/startup', 'ServerController@getStartup')->name('server.settings.startup'); 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('/sftp', 'ServerController@postSettingsSFTP');
Route::post('/startup', 'ServerController@postSettingsStartup'); Route::post('/startup', 'ServerController@postSettingsStartup');