Finish subuser controller

This commit is contained in:
Dane Everitt 2017-09-04 18:12:13 -05:00
parent 7222754580
commit dc310ffdea
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
16 changed files with 524 additions and 161 deletions

View file

@ -112,8 +112,6 @@ interface RepositoryInterface
*
* @param array $fields
* @return mixed
*
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
*/
public function findWhere(array $fields);

View file

@ -36,6 +36,16 @@ interface SubuserRepositoryInterface extends RepositoryInterface
*/
public function getWithServer($id);
/**
* Return a subuser with the associated permissions relationship.
*
* @param int $id
* @return \Illuminate\Database\Eloquent\Collection
*
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
*/
public function getWithPermissions($id);
/**
* Find a subuser and return with server and permissions relationships.
*

View file

@ -24,62 +24,118 @@
namespace Pterodactyl\Http\Controllers\Server;
use Log;
use Auth;
use Alert;
use Pterodactyl\Models;
use Illuminate\Contracts\Session\Session;
use Prologue\Alerts\AlertsMessageBag;
use Pterodactyl\Contracts\Repository\SubuserRepositoryInterface;
use Illuminate\Http\Request;
use Pterodactyl\Exceptions\DisplayException;
use Pterodactyl\Http\Controllers\Controller;
use Pterodactyl\Repositories\SubuserRepository;
use Pterodactyl\Exceptions\DisplayValidationException;
use Pterodactyl\Models\Permission;
use Pterodactyl\Services\Subusers\SubuserCreationService;
use Pterodactyl\Services\Subusers\SubuserDeletionService;
use Pterodactyl\Services\Subusers\SubuserUpdateService;
use Pterodactyl\Traits\Controllers\JavascriptInjection;
class SubuserController extends Controller
{
use JavascriptInjection;
/**
* @var \Prologue\Alerts\AlertsMessageBag
*/
protected $alert;
/**
* @var \Pterodactyl\Contracts\Repository\SubuserRepositoryInterface
*/
protected $repository;
/**
* @var \Illuminate\Contracts\Session\Session
*/
protected $session;
/**
* @var \Pterodactyl\Services\Subusers\SubuserCreationService
*/
protected $subuserCreationService;
/**
* @var \Pterodactyl\Services\Subusers\SubuserDeletionService
*/
protected $subuserDeletionService;
/**
* @var \Pterodactyl\Services\Subusers\SubuserUpdateService
*/
protected $subuserUpdateService;
/**
* SubuserController constructor.
*
* @param \Prologue\Alerts\AlertsMessageBag $alert
* @param \Illuminate\Contracts\Session\Session $session
* @param \Pterodactyl\Services\Subusers\SubuserCreationService $subuserCreationService
* @param \Pterodactyl\Services\Subusers\SubuserDeletionService $subuserDeletionService
* @param \Pterodactyl\Contracts\Repository\SubuserRepositoryInterface $repository
* @param \Pterodactyl\Services\Subusers\SubuserUpdateService $subuserUpdateService
*/
public function __construct(
AlertsMessageBag $alert,
Session $session,
SubuserCreationService $subuserCreationService,
SubuserDeletionService $subuserDeletionService,
SubuserRepositoryInterface $repository,
SubuserUpdateService $subuserUpdateService
) {
$this->alert = $alert;
$this->repository = $repository;
$this->session = $session;
$this->subuserCreationService = $subuserCreationService;
$this->subuserDeletionService = $subuserDeletionService;
$this->subuserUpdateService = $subuserUpdateService;
}
/**
* Displays the subuser overview index.
*
* @param \Illuminate\Http\Request $request
* @param string $uuid
* @return \Illuminate\View\View
*
* @throws \Illuminate\Auth\Access\AuthorizationException
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
*/
public function index(Request $request, $uuid)
public function index()
{
$server = Models\Server::byUuid($uuid)->load('subusers.user');
$server = $this->session->get('server_data.model');
$this->authorize('list-subusers', $server);
$server->js();
$this->injectJavascript();
return view('server.users.index', [
'server' => $server,
'node' => $server->node,
'subusers' => $server->subusers,
'subusers' => $this->repository->findWhere([['server_id', '=', $server->id]]),
]);
}
/**
* Displays the a single subuser overview.
*
* @param \Illuminate\Http\Request $request
* @param string $uuid
* @param int $id
* @param string $uuid
* @param int $id
* @return \Illuminate\View\View
*
* @throws \Illuminate\Auth\Access\AuthorizationException
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
*/
public function view(Request $request, $uuid, $id)
public function view($uuid, $id)
{
$server = Models\Server::byUuid($uuid)->load('node');
$server = $this->session->get('server_data.model');
$this->authorize('view-subuser', $server);
$subuser = Models\Subuser::with('permissions', 'user')
->where('server_id', $server->id)->findOrFail($id);
$server->js();
$subuser = $this->repository->getWithPermissions($id);
$this->injectJavascript();
return view('server.users.view', [
'server' => $server,
'node' => $server->node,
'subuser' => $subuser,
'permlist' => Models\Permission::listPermissions(),
'permlist' => Permission::getPermissions(),
'permissions' => $subuser->permissions->mapWithKeys(function ($item, $key) {
return [$item->permission => true];
}),
@ -93,63 +149,38 @@ class SubuserController extends Controller
* @param string $uuid
* @param int $id
* @return \Illuminate\Http\RedirectResponse
*
* @throws \Illuminate\Auth\Access\AuthorizationException
* @throws \Pterodactyl\Exceptions\DisplayException
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
*/
public function update(Request $request, $uuid, $id)
{
$server = Models\Server::byUuid($uuid);
$server = $this->session->get('server_data.model');
$this->authorize('edit-subuser', $server);
$subuser = Models\Subuser::where('server_id', $server->id)->findOrFail($id);
$this->subuserUpdateService->handle($id, $request->input('permissions', []));
$this->alert->success(trans('server.users.user_updated'))->flash();
try {
if ($subuser->user_id === Auth::user()->id) {
throw new DisplayException('You are not authorized to edit you own account.');
}
$repo = new SubuserRepository;
$repo->update($subuser->id, [
'permissions' => $request->input('permissions'),
'server' => $server->id,
'user' => $subuser->user_id,
]);
Alert::success('Subuser permissions have successfully been updated.')->flash();
} catch (DisplayValidationException $ex) {
return redirect()->route('server.subusers.view', [
'uuid' => $uuid,
'id' => $id,
])->withErrors(json_decode($ex->getMessage()));
} catch (DisplayException $ex) {
Alert::danger($ex->getMessage())->flash();
} catch (\Exception $ex) {
Log::error($ex);
Alert::danger('An unknown error occured while attempting to update this subuser.')->flash();
}
return redirect()->route('server.subusers.view', [
'uuid' => $uuid,
'id' => $id,
]);
return redirect()->route('server.subusers.view', ['uuid' => $uuid, 'id' => $id]);
}
/**
* Display new subuser creation page.
*
* @param \Illuminate\Http\Request $request
* @param string $uuid
* @return \Illuminate\View\View
*
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
public function create(Request $request, $uuid)
public function create()
{
$server = Models\Server::byUuid($uuid);
$server = $this->session->get('server_data.model');
$this->authorize('create-subuser', $server);
$server->js();
return view('server.users.new', [
'server' => $server,
'permissions' => Models\Permission::listPermissions(),
'node' => $server->node,
]);
$this->injectJavascript();
return view('server.users.new', ['permissions' => Permission::getPermissions()]);
}
/**
@ -158,64 +189,47 @@ class SubuserController extends Controller
* @param \Illuminate\Http\Request $request
* @param string $uuid
* @return \Illuminate\Http\RedirectResponse
*
* @throws \Exception
* @throws \Illuminate\Auth\Access\AuthorizationException
* @throws \Pterodactyl\Exceptions\DisplayException
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
* @throws \Pterodactyl\Exceptions\Service\Subuser\ServerSubuserExistsException
* @throws \Pterodactyl\Exceptions\Service\Subuser\UserIsServerOwnerException
*/
public function store(Request $request, $uuid)
{
$server = Models\Server::byUuid($uuid);
$server = $this->session->get('server_data.model');
$this->authorize('create-subuser', $server);
try {
$repo = new SubuserRepository;
$subuser = $repo->create($server->id, $request->only([
'permissions', 'email',
]));
Alert::success('Successfully created new subuser.')->flash();
$subuser = $this->subuserCreationService->handle($server, $request->input('email'), $request->input('permissions', []));
$this->alert->success(trans('server.users.user_assigned'))->flash();
return redirect()->route('server.subusers.view', [
'uuid' => $uuid,
'id' => $subuser->id,
]);
} catch (DisplayValidationException $ex) {
return redirect()->route('server.subusers.new', $uuid)->withErrors(json_decode($ex->getMessage()))->withInput();
} catch (DisplayException $ex) {
Alert::danger($ex->getMessage())->flash();
} catch (\Exception $ex) {
Log::error($ex);
Alert::danger('An unknown error occured while attempting to add a new subuser.')->flash();
}
return redirect()->route('server.subusers.new', $uuid)->withInput();
return redirect()->route('server.subusers.view', [
'uuid' => $uuid,
'id' => $subuser->id,
]);
}
/**
* Handles deleting a subuser.
*
* @param \Illuminate\Http\Request $request
* @param string $uuid
* @param int $id
* @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
* @param string $uuid
* @param int $id
* @return \Illuminate\Http\Response
*
* @throws \Illuminate\Auth\Access\AuthorizationException
* @throws \Pterodactyl\Exceptions\DisplayException
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
*/
public function delete(Request $request, $uuid, $id)
public function delete($uuid, $id)
{
$server = Models\Server::byUuid($uuid);
$server = $this->session->get('server_data.model');
$this->authorize('delete-subuser', $server);
try {
$subuser = Models\Subuser::where('server_id', $server->id)->findOrFail($id);
$this->subuserDeletionService->handle($id);
$repo = new SubuserRepository;
$repo->delete($subuser->id);
return response('', 204);
} catch (DisplayException $ex) {
response()->json([
'error' => $ex->getMessage(),
], 422);
} catch (\Exception $ex) {
Log::error($ex);
response()->json([
'error' => 'An unknown error occured while attempting to delete this subuser.',
], 503);
}
return response('', 204);
}
}

View file

@ -25,27 +25,9 @@
namespace Pterodactyl\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class AdminAuthenticate
{
/**
* The Guard implementation.
*
* @var \Illuminate\Contracts\Auth\Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* @param \Illuminate\Contracts\Auth\Guard $auth
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
@ -55,15 +37,15 @@ class AdminAuthenticate
*/
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
if (! $request->user()) {
if ($request->expectsJson() || $request->json()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('auth/login');
}
}
if ($this->auth->user()->root_admin !== 1) {
if (! $request->user()->root_admin) {
return abort(403);
}

View file

@ -0,0 +1,84 @@
<?php
/*
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace Pterodactyl\Http\Middleware\Server;
use Closure;
use Illuminate\Contracts\Session\Session;
use Pterodactyl\Contracts\Repository\SubuserRepositoryInterface;
use Pterodactyl\Exceptions\DisplayException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class SubuserAccess
{
/**
* @var \Pterodactyl\Contracts\Repository\SubuserRepositoryInterface
*/
protected $repository;
/**
* @var \Illuminate\Contracts\Session\Session
*/
protected $session;
/**
* SubuserAccess constructor.
*
* @param \Illuminate\Contracts\Session\Session $session
* @param \Pterodactyl\Contracts\Repository\SubuserRepositoryInterface $repository
*/
public function __construct(Session $session, SubuserRepositoryInterface $repository)
{
$this->repository = $repository;
$this->session = $session;
}
/**
* Determine if a user has permission to access a subuser.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*
* @throws \Pterodactyl\Exceptions\DisplayException
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
*/
public function handle($request, Closure $next)
{
$server = $this->session->get('server_data.model');
$subuser = $this->repository->find($request->route()->parameter('subuser', 0));
if ($subuser->server_id !== $server->id) {
throw new NotFoundHttpException;
}
if ($request->method() === 'PATCH') {
if ($subuser->user_id === $request->user()->id) {
throw new DisplayException(trans('exceptions.subusers.editing_self'));
}
}
return $next($request);
}
}

View file

@ -46,7 +46,22 @@ class SubuserRepository extends EloquentRepository implements SubuserRepositoryI
{
Assert::numeric($id, 'First argument passed to getWithServer must be numeric, received %s.');
$instance = $this->getBuilder()->with('server')->find($id, $this->getColumns());
$instance = $this->getBuilder()->with('server', 'user')->find($id, $this->getColumns());
if (! $instance) {
throw new RecordNotFoundException;
}
return $instance;
}
/**
* {@inheritdoc}
*/
public function getWithPermissions($id)
{
Assert::numeric($id, 'First argument passed to getWithPermissions must be numeric, received %s.');
$instance = $this->getBuilder()->with('permissions', 'user')->find($id, $this->getColumns());
if (! $instance) {
throw new RecordNotFoundException;
}
@ -61,7 +76,7 @@ class SubuserRepository extends EloquentRepository implements SubuserRepositoryI
{
Assert::numeric($id, 'First argument passed to getWithServerAndPermissions must be numeric, received %s.');
$instance = $this->getBuilder()->with(['server', 'permission'])->find($id, $this->getColumns());
$instance = $this->getBuilder()->with('server', 'permission', 'user')->find($id, $this->getColumns());
if (! $instance) {
throw new RecordNotFoundException;
}

View file

@ -25,6 +25,7 @@
namespace Pterodactyl\Services\Subusers;
use Illuminate\Log\Writer;
use Pterodactyl\Exceptions\Repository\RecordNotFoundException;
use Pterodactyl\Models\Server;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Database\ConnectionInterface;
@ -81,6 +82,18 @@ class SubuserCreationService
*/
protected $writer;
/**
* SubuserCreationService constructor.
*
* @param \Illuminate\Database\ConnectionInterface $connection
* @param \Pterodactyl\Services\Users\UserCreationService $userCreationService
* @param \Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface $daemonRepository
* @param \Pterodactyl\Services\Subusers\PermissionCreationService $permissionService
* @param \Pterodactyl\Contracts\Repository\ServerRepositoryInterface $serverRepository
* @param \Pterodactyl\Contracts\Repository\SubuserRepositoryInterface $subuserRepository
* @param \Pterodactyl\Contracts\Repository\UserRepositoryInterface $userRepository
* @param \Illuminate\Log\Writer $writer
*/
public function __construct(
ConnectionInterface $connection,
UserCreationService $userCreationService,
@ -120,16 +133,10 @@ class SubuserCreationService
$server = $this->serverRepository->find($server);
}
$user = $this->userRepository->findWhere([['email', '=', $email]]);
if (is_null($user)) {
$user = $this->userCreationService->handle([
'email' => $email,
'username' => substr(strtok($email, '@'), 0, 8),
'name_first' => 'Server',
'name_last' => 'Subuser',
'root_admin' => false,
]);
} else {
$this->connection->beginTransaction();
try {
$user = $this->userRepository->findFirstWhere([['email', '=', $email]]);
if ($server->owner_id === $user->id) {
throw new UserIsServerOwnerException(trans('exceptions.subusers.user_is_owner'));
}
@ -138,9 +145,16 @@ class SubuserCreationService
if ($subuserCount !== 0) {
throw new ServerSubuserExistsException(trans('exceptions.subusers.subuser_exists'));
}
} catch (RecordNotFoundException $exception) {
$user = $this->userCreationService->handle([
'email' => $email,
'username' => substr(strtok($email, '@'), 0, 8) . '_' . str_random(6),
'name_first' => 'Server',
'name_last' => 'Subuser',
'root_admin' => false,
]);
}
$this->connection->beginTransaction();
$subuser = $this->subuserRepository->create([
'user_id' => $user->id,
'server_id' => $server->id,

View file

@ -55,6 +55,7 @@ return [
'invalid_archive_exception' => 'The pack archive provided appears to be missing a required archive.tar.gz or import.json file in the base directory.',
],
'subusers' => [
'editing_self' => 'Editing your own subuser account is not permitted.',
'user_is_owner' => 'You cannot add the server owner as a subuser for this server.',
'subuser_exists' => 'A user with that email address is already assigned as a subuser for this server.',
],

View file

@ -44,6 +44,8 @@ return [
'list' => 'Accounts with Access',
'add' => 'Add New Subuser',
'update' => 'Update Subuser',
'user_assigned' => 'Successfully assigned a new subuser to this server.',
'user_updated' => 'Successfully updated permissions.',
'edit' => [
'header' => 'Edit Subuser',
'header_sub' => 'Modify user\'s access to server.',

View file

@ -77,7 +77,7 @@
{{--<li>--}}
{{--<a href="#" data-action="control-sidebar" data-toggle="tooltip" data-placement="bottom" title="{{ @trans('strings.servers') }}"><i class="fa fa-server"></i></a>--}}
{{--</li>--}}
@if(Auth::user()->isRootAdmin())
@if(Auth::user()->root_admin)
<li>
<li><a href="{{ route('admin.index') }}" data-toggle="tooltip" data-placement="bottom" title="{{ @trans('strings.admin_cp') }}"><i class="fa fa-gears"></i></a></li>
</li>

View file

@ -44,7 +44,7 @@
<label class="control-label">@lang('server.users.new.email')</label>
<div>
{!! csrf_field() !!}
<input type="email" class="form-control" name="email" />
<input type="email" class="form-control" name="email" value="{{ old('email') }}" />
<p class="text-muted small">@lang('server.users.new.email_help')</p>
</div>
</div>

View file

@ -55,6 +55,7 @@
<a id="selectAllCheckboxes" class="btn btn-sm btn-default">@lang('strings.select_all')</a>
<a id="unselectAllCheckboxes" class="btn btn-sm btn-default">@lang('strings.select_none')</a>
</div>
{!! method_field('PATCH') !!}
<input type="submit" name="submit" value="@lang('server.users.update')" class="pull-right btn btn-sm btn-primary" />
</div>
@endcan

View file

@ -21,6 +21,8 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
use Pterodactyl\Http\Middleware\Server\SubuserAccess;
Route::get('/', 'ConsoleController@index')->name('server.index');
Route::get('/console', 'ConsoleController@console')->name('server.console');
@ -71,12 +73,13 @@ Route::group(['prefix' => 'files'], function () {
Route::group(['prefix' => 'users'], function () {
Route::get('/', 'SubuserController@index')->name('server.subusers');
Route::get('/new', 'SubuserController@create')->name('server.subusers.new');
Route::get('/view/{id}', 'SubuserController@view')->name('server.subusers.view');
Route::get('/view/{subuser}', 'SubuserController@view')->middleware(SubuserAccess::class)->name('server.subusers.view');
Route::post('/new', 'SubuserController@store');
Route::post('/view/{id}', 'SubuserController@update');
Route::delete('/delete/{id}', 'SubuserController@delete')->name('server.subusers.delete');
Route::patch('/view/{subuser}', 'SubuserController@update')->middleware(SubuserAccess::class);
Route::delete('/delete/{subuser}', 'SubuserController@delete')->middleware(SubuserAccess::class)->name('server.subusers.delete');
});
/*

View file

@ -159,10 +159,11 @@ trait ControllerAssertionsTrait
*
* @param string $route
* @param mixed $response
* @param array $args
*/
public function assertRedirectRouteEquals($route, $response)
public function assertRedirectRouteEquals($route, $response, array $args = [])
{
PHPUnit_Framework_Assert::assertEquals(route($route), $response->getTargetUrl());
PHPUnit_Framework_Assert::assertEquals(route($route, $args), $response->getTargetUrl());
}
/**

View file

@ -0,0 +1,234 @@
<?php
/*
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace Tests\Unit\Http\Controllers\Server;
use Illuminate\Contracts\Session\Session;
use Illuminate\Http\Request;
use Mockery as m;
use Prologue\Alerts\AlertsMessageBag;
use Pterodactyl\Contracts\Repository\SubuserRepositoryInterface;
use Pterodactyl\Http\Controllers\Server\SubuserController;
use Pterodactyl\Models\Permission;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\Subuser;
use Pterodactyl\Services\Subusers\SubuserCreationService;
use Pterodactyl\Services\Subusers\SubuserDeletionService;
use Pterodactyl\Services\Subusers\SubuserUpdateService;
use Tests\Assertions\ControllerAssertionsTrait;
use Tests\TestCase;
class SubuserControllerTest extends TestCase
{
use ControllerAssertionsTrait;
/**
* @var \Prologue\Alerts\AlertsMessageBag
*/
protected $alert;
/**
* @var \Pterodactyl\Http\Controllers\Server\SubuserController
*/
protected $controller;
/**
* @var \Pterodactyl\Contracts\Repository\SubuserRepositoryInterface
*/
protected $repository;
/**
* @var \Illuminate\Http\Request
*/
protected $request;
/**
* @var \Illuminate\Contracts\Session\Session
*/
protected $session;
/**
* @var \Pterodactyl\Services\Subusers\SubuserCreationService
*/
protected $subuserCreationService;
/**
* @var \Pterodactyl\Services\Subusers\SubuserDeletionService
*/
protected $subuserDeletionService;
/**
* @var \Pterodactyl\Services\Subusers\SubuserUpdateService
*/
protected $subuserUpdateService;
/**
* Setup tests.
*/
public function setUp()
{
parent::setUp();
$this->alert = m::mock(AlertsMessageBag::class);
$this->repository = m::mock(SubuserRepositoryInterface::class);
$this->request = m::mock(Request::class);
$this->session = m::mock(Session::class);
$this->subuserCreationService = m::mock(SubuserCreationService::class);
$this->subuserDeletionService = m::mock(SubuserDeletionService::class);
$this->subuserUpdateService = m::mock(SubuserUpdateService::class);
$this->controller = m::mock(SubuserController::class, [
$this->alert,
$this->session,
$this->subuserCreationService,
$this->subuserDeletionService,
$this->repository,
$this->subuserUpdateService,
])->makePartial();
}
/*
* Test index controller.
*/
public function testIndexController()
{
$server = factory(Server::class)->make();
$this->session->shouldReceive('get')->with('server_data.model')->once()->andReturn($server);
$this->controller->shouldReceive('authorize')->with('list-subusers', $server)->once()->andReturnNull();
$this->controller->shouldReceive('injectJavascript')->withNoArgs()->once()->andReturnNull();
$this->repository->shouldReceive('findWhere')->with([['server_id', '=', $server->id]])->once()->andReturn([]);
$response = $this->controller->index();
$this->assertIsViewResponse($response);
$this->assertViewNameEquals('server.users.index', $response);
$this->assertViewHasKey('subusers', $response);
}
/**
* Test view controller.
*/
public function testViewController()
{
$subuser = factory(Subuser::class)->make([
'permissions' => collect([
(object) ['permission' => 'some.permission'],
(object) ['permission' => 'another.permission'],
]),
]);
$server = factory(Server::class)->make();
$this->session->shouldReceive('get')->with('server_data.model')->once()->andReturn($server);
$this->controller->shouldReceive('authorize')->with('view-subuser', $server)->once()->andReturnNull();
$this->repository->shouldReceive('getWithPermissions')->with(1234)->once()->andReturn($subuser);
$this->controller->shouldReceive('injectJavascript')->withNoArgs()->once()->andReturnNull();
$response = $this->controller->view($server->uuid, 1234);
$this->assertIsViewResponse($response);
$this->assertViewNameEquals('server.users.view', $response);
$this->assertViewHasKey('subuser', $response);
$this->assertViewHasKey('permlist', $response);
$this->assertViewHasKey('permissions', $response);
$this->assertViewKeyEquals('subuser', $subuser, $response);
$this->assertViewKeyEquals('permlist', Permission::getPermissions(), $response);
$this->assertViewKeyEquals('permissions', collect([
'some.permission' => true,
'another.permission' => true,
]), $response);
}
/**
* Test the update controller.
*/
public function testUpdateController()
{
$server = factory(Server::class)->make();
$this->session->shouldReceive('get')->with('server_data.model')->once()->andReturn($server);
$this->controller->shouldReceive('authorize')->with('edit-subuser', $server)->once()->andReturnNull();
$this->request->shouldReceive('input')->with('permissions', [])->once()->andReturn(['some.permission']);
$this->subuserUpdateService->shouldReceive('handle')->with(1234, ['some.permission'])->once()->andReturnNull();
$this->alert->shouldReceive('success')->with(trans('server.users.user_updated'))->once()->andReturnSelf()
->shouldReceive('flash')->withNoArgs()->once()->andReturnNull();
$response = $this->controller->update($this->request, $server->uuid, 1234);
$this->assertIsRedirectResponse($response);
$this->assertRedirectRouteEquals('server.subusers.view', $response, ['uuid' => $server->uuid, 'id' => 1234]);
}
/**
* Test the create controller.
*/
public function testCreateController()
{
$server = factory(Server::class)->make();
$this->session->shouldReceive('get')->with('server_data.model')->once()->andReturn($server);
$this->controller->shouldReceive('authorize')->with('create-subuser', $server)->once()->andReturnNull();
$this->controller->shouldReceive('injectJavascript')->withNoArgs()->once()->andReturnNull();
$response = $this->controller->create();
$this->assertIsViewResponse($response);
$this->assertViewNameEquals('server.users.new', $response);
$this->assertViewHasKey('permissions', $response);
$this->assertViewKeyEquals('permissions', Permission::getPermissions(), $response);
}
/**
* Test the store controller.
*/
public function testStoreController()
{
$server = factory(Server::class)->make();
$subuser = factory(Subuser::class)->make();
$this->session->shouldReceive('get')->with('server_data.model')->once()->andReturn($server);
$this->controller->shouldReceive('authorize')->with('create-subuser', $server)->once()->andReturnNull();
$this->request->shouldReceive('input')->with('email')->once()->andReturn('user@test.com');
$this->request->shouldReceive('input')->with('permissions', [])->once()->andReturn(['some.permission']);
$this->subuserCreationService->shouldReceive('handle')->with($server, 'user@test.com', ['some.permission'])->once()->andReturn($subuser);
$this->alert->shouldReceive('success')->with(trans('server.users.user_assigned'))->once()->andReturnSelf()
->shouldReceive('flash')->withNoArgs()->once()->andReturnNull();
$response = $this->controller->store($this->request, $server->uuid);
$this->assertIsRedirectResponse($response);
$this->assertRedirectRouteEquals('server.subusers.view', $response, ['uuid' => $server->uuid, 'id' => $subuser->id]);
}
/**
* Test the delete controller.
*/
public function testDeleteController()
{
$server = factory(Server::class)->make();
$this->session->shouldReceive('get')->with('server_data.model')->once()->andReturn($server);
$this->controller->shouldReceive('authorize')->with('delete-subuser', $server)->once()->andReturnNull();
$this->subuserDeletionService->shouldReceive('handle')->with(1234)->once()->andReturnNull();
$response = $this->controller->delete($server->uuid, 1234);
$this->assertIsResponse($response);
$this->assertResponseCodeEquals(204, $response);
}
}

View file

@ -25,6 +25,7 @@
namespace Tests\Unit\Services\Subusers;
use Mockery as m;
use Pterodactyl\Exceptions\Repository\RecordNotFoundException;
use Tests\TestCase;
use Illuminate\Log\Writer;
use phpmock\phpunit\PHPMock;
@ -100,6 +101,7 @@ class SubuserCreationServiceTest extends TestCase
parent::setUp();
$this->getFunctionMock('\\Pterodactyl\\Services\\Subusers', 'bin2hex')->expects($this->any())->willReturn('bin2hex');
$this->getFunctionMock('\\Pterodactyl\\Services\\Subusers', 'str_random')->expects($this->any())->willReturn('123456');
$this->connection = m::mock(ConnectionInterface::class);
$this->daemonRepository = m::mock(DaemonServerRepositoryInterface::class);
@ -132,16 +134,16 @@ class SubuserCreationServiceTest extends TestCase
$user = factory(User::class)->make();
$subuser = factory(Subuser::class)->make(['user_id' => $user->id, 'server_id' => $server->id]);
$this->userRepository->shouldReceive('findWhere')->with([['email', '=', $user->email]])->once()->andReturnNull();
$this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->userRepository->shouldReceive('findFirstWhere')->with([['email', '=', $user->email]])->once()->andThrow(new RecordNotFoundException);
$this->userCreationService->shouldReceive('handle')->with([
'email' => $user->email,
'username' => substr(strtok($user->email, '@'), 0, 8),
'username' => substr(strtok($user->email, '@'), 0, 8) . '_' . '123456',
'name_first' => 'Server',
'name_last' => 'Subuser',
'root_admin' => false,
])->once()->andReturn($user);
$this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->subuserRepository->shouldReceive('create')->with([
'user_id' => $user->id,
'server_id' => $server->id,
@ -172,13 +174,13 @@ class SubuserCreationServiceTest extends TestCase
$user = factory(User::class)->make();
$subuser = factory(Subuser::class)->make(['user_id' => $user->id, 'server_id' => $server->id]);
$this->userRepository->shouldReceive('findWhere')->with([['email', '=', $user->email]])->once()->andReturn($user);
$this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->userRepository->shouldReceive('findFirstWhere')->with([['email', '=', $user->email]])->once()->andReturn($user);
$this->subuserRepository->shouldReceive('findCountWhere')->with([
['user_id', '=', $user->id],
['server_id', '=', $server->id],
])->once()->andReturn(0);
$this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->subuserRepository->shouldReceive('create')->with([
'user_id' => $user->id,
'server_id' => $server->id,
@ -207,7 +209,8 @@ class SubuserCreationServiceTest extends TestCase
$user = factory(User::class)->make();
$server = factory(Server::class)->make(['owner_id' => $user->id]);
$this->userRepository->shouldReceive('findWhere')->with([['email', '=', $user->email]])->once()->andReturn($user);
$this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->userRepository->shouldReceive('findFirstWhere')->with([['email', '=', $user->email]])->once()->andReturn($user);
try {
$this->service->handle($server, $user->email, []);
@ -225,7 +228,8 @@ class SubuserCreationServiceTest extends TestCase
$user = factory(User::class)->make();
$server = factory(Server::class)->make();
$this->userRepository->shouldReceive('findWhere')->with([['email', '=', $user->email]])->once()->andReturn($user);
$this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->userRepository->shouldReceive('findFirstWhere')->with([['email', '=', $user->email]])->once()->andReturn($user);
$this->subuserRepository->shouldReceive('findCountWhere')->with([
['user_id', '=', $user->id],
['server_id', '=', $server->id],