More service structure testing and configuration

Tests aren't working as well as I had hoped, so a lot are commented out while I wait to hear back on this bug causing them to fail.
This commit is contained in:
Dane Everitt 2017-06-24 19:49:09 -05:00
parent ce2b2447d0
commit 2235481765
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
18 changed files with 755 additions and 401 deletions

View file

@ -0,0 +1,50 @@
<?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\Exceptions\Model;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Validation\ValidationException;
use Illuminate\Contracts\Support\MessageProvider;
class DataValidationException extends ValidationException implements MessageProvider
{
/**
* DataValidationException constructor.
*
* @param \Illuminate\Contracts\Validation\Validator $validator
*/
public function __construct(Validator $validator)
{
parent::__construct($validator);
}
/**
* @return \Illuminate\Support\MessageBag
*/
public function getMessageBag()
{
return $this->validator->errors();
}
}

View file

@ -47,20 +47,20 @@ class UserController extends Controller
/** /**
* @var \Pterodactyl\Models\User * @var \Pterodactyl\Models\User
*/ */
protected $userModel; protected $model;
/** /**
* UserController constructor. * UserController constructor.
* *
* @param \Prologue\Alerts\AlertsMessageBag $alert * @param \Prologue\Alerts\AlertsMessageBag $alert
* @param \Pterodactyl\Services\UserService $service * @param \Pterodactyl\Services\UserService $service
* @param \Pterodactyl\Models\User $userModel * @param \Pterodactyl\Models\User $model
*/ */
public function __construct(AlertsMessageBag $alert, UserService $service, User $userModel) public function __construct(AlertsMessageBag $alert, UserService $service, User $model)
{ {
$this->alert = $alert; $this->alert = $alert;
$this->service = $service; $this->service = $service;
$this->userModel = $userModel; $this->model = $model;
} }
/** /**
@ -71,7 +71,7 @@ class UserController extends Controller
*/ */
public function index(Request $request) public function index(Request $request)
{ {
$users = $this->userModel->withCount('servers', 'subuserOf'); $users = $this->model->newQuery()->withCount('servers', 'subuserOf');
if (! is_null($request->input('query'))) { if (! is_null($request->input('query'))) {
$users->search($request->input('query')); $users->search($request->input('query'));
@ -108,13 +108,19 @@ class UserController extends Controller
/** /**
* Delete a user from the system. * Delete a user from the system.
* *
* @param \Illuminate\Http\Request $request
* @param \Pterodactyl\Models\User $user * @param \Pterodactyl\Models\User $user
* @return \Illuminate\Http\RedirectResponse * @return \Illuminate\Http\RedirectResponse
* *
* @throws \Exception * @throws \Exception
* @throws \Pterodactyl\Exceptions\DisplayException
*/ */
public function delete(User $user) public function delete(Request $request, User $user)
{ {
if ($request->user()->id === $user->id) {
throw new DisplayException('Cannot delete your own account.');
}
try { try {
$this->service->delete($user->id); $this->service->delete($user->id);
@ -149,6 +155,8 @@ class UserController extends Controller
* @param \Pterodactyl\Http\Requests\Admin\UserFormRequest $request * @param \Pterodactyl\Http\Requests\Admin\UserFormRequest $request
* @param \Pterodactyl\Models\User $user * @param \Pterodactyl\Models\User $user
* @return \Illuminate\Http\RedirectResponse * @return \Illuminate\Http\RedirectResponse
*
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
*/ */
public function update(UserFormRequest $request, User $user) public function update(UserFormRequest $request, User $user)
{ {
@ -166,7 +174,7 @@ class UserController extends Controller
*/ */
public function json(Request $request) public function json(Request $request)
{ {
return $this->userModel->search($request->input('q'))->all([ return $this->model->search($request->input('q'))->all([
'id', 'email', 'username', 'name_first', 'name_last', 'id', 'email', 'username', 'name_first', 'name_last',
])->transform(function ($item) { ])->transform(function ($item) {
$item->md5 = md5(strtolower($item->email)); $item->md5 = md5(strtolower($item->email));

View file

@ -35,6 +35,10 @@ class LocationRequest extends AdminFormRequest
*/ */
public function rules() public function rules()
{ {
return app()->make(Location::class)->getRules(); if ($this->method() === 'PATCH') {
return Location::getUpdateRulesForId($this->location->id);
}
return Location::getCreateRules();
} }
} }

View file

@ -25,46 +25,19 @@
namespace Pterodactyl\Http\Requests\Admin; namespace Pterodactyl\Http\Requests\Admin;
use Pterodactyl\Models\User; use Pterodactyl\Models\User;
use Pterodactyl\Contracts\Repositories\UserInterface;
class UserFormRequest extends AdminFormRequest class UserFormRequest extends AdminFormRequest
{ {
/**
* {@inheritdoc}
*/
public function repository()
{
return UserInterface::class;
}
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function rules() public function rules()
{ {
if ($this->method() === 'PATCH') { if ($this->method() === 'PATCH') {
return [ return User::getUpdateRulesForId($this->user->id);
'email' => 'required|email|unique:users,email,' . $this->user->id,
'username' => 'required|alpha_dash|between:1,255|unique:users,username, ' . $this->user->id . '|' . User::USERNAME_RULES,
'name_first' => 'required|string|between:1,255',
'name_last' => 'required|string|between:1,255',
'password' => 'sometimes|nullable|' . User::PASSWORD_RULES,
'root_admin' => 'required|boolean',
// 'language' => 'sometimes|required|string|min:1|max:5',
// 'use_totp' => 'sometimes|required|boolean',
// 'totp_secret' => 'sometimes|required|size:16',
];
} }
return [ return User::getCreateRules();
'email' => 'required|email|unique:users,email',
'username' => 'required|alpha_dash|between:1,255|unique:users,username|' . User::USERNAME_RULES,
'name_first' => 'required|string|between:1,255',
'name_last' => 'required|string|between:1,255',
'password' => 'sometimes|nullable|' . User::PASSWORD_RULES,
'root_admin' => 'required|boolean',
'external_id' => 'sometimes|nullable|numeric|unique:users,external_id',
];
} }
public function normalize() public function normalize()

View file

@ -24,12 +24,14 @@
namespace Pterodactyl\Models; namespace Pterodactyl\Models;
use Watson\Validating\ValidatingTrait; use Sofa\Eloquence\Eloquence;
use Sofa\Eloquence\Validable;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Sofa\Eloquence\Contracts\Validable as ValidableContract;
class Location extends Model class Location extends Model implements ValidableContract
{ {
use ValidatingTrait; use Eloquence, Validable;
/** /**
* The table associated with the model. * The table associated with the model.
@ -50,9 +52,19 @@ class Location extends Model
* *
* @var array * @var array
*/ */
protected $rules = [ protected static $applicationRules = [
'short' => 'required|string|between:1,60|unique:locations,short', 'short' => 'required',
'long' => 'required|string|between:1,255', 'long' => 'required',
];
/**
* Rules ensuring that the raw data stored in the database meets expectations.
*
* @var array
*/
protected static $dataIntegrityRules = [
'short' => 'string|between:1,60|unique:locations,short',
'long' => 'string|between:1,255',
]; ];
/** /**

View file

@ -26,26 +26,29 @@ namespace Pterodactyl\Models;
use Hash; use Hash;
use Google2FA; use Google2FA;
use Sofa\Eloquence\Eloquence;
use Sofa\Eloquence\Validable;
use Illuminate\Auth\Authenticatable; use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notifiable;
use Pterodactyl\Exceptions\DisplayException; use Pterodactyl\Exceptions\DisplayException;
use Nicolaslopezj\Searchable\SearchableTrait;
use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable; use Illuminate\Foundation\Auth\Access\Authorizable;
use Sofa\Eloquence\Contracts\Validable as ValidableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract; use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Pterodactyl\Notifications\SendPasswordReset as ResetPasswordNotification; use Pterodactyl\Notifications\SendPasswordReset as ResetPasswordNotification;
class User extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract class User extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract, ValidableContract
{ {
use Authenticatable, Authorizable, CanResetPassword, Notifiable, SearchableTrait; use Authenticatable, Authorizable, CanResetPassword, Eloquence, Notifiable, Validable;
/** /**
* The rules for user passwords. * The rules for user passwords.
* *
* @var string * @var string
* @deprecated
*/ */
const PASSWORD_RULES = 'regex:((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,})'; const PASSWORD_RULES = 'regex:((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,})';
@ -101,16 +104,53 @@ class User extends Model implements AuthenticatableContract, AuthorizableContrac
* @var array * @var array
*/ */
protected $searchable = [ protected $searchable = [
'columns' => [
'email' => 10, 'email' => 10,
'username' => 9, 'username' => 9,
'name_first' => 6, 'name_first' => 6,
'name_last' => 6, 'name_last' => 6,
'uuid' => 1, 'uuid' => 1,
],
]; ];
protected $query; /**
* Default values for specific fields in the database.
*
* @var array
*/
protected $attributes = [
'root_admin' => false,
'language' => 'en',
'use_totp' => false,
'totp_secret' => null,
];
/**
* Rules verifying that the data passed in forms is valid and meets application logic rules.
* @var array
*/
protected static $applicationRules = [
'email' => 'required|email',
'username' => 'required|alpha_dash',
'name_first' => 'required|string',
'name_last' => 'required|string',
'password' => 'sometimes|regex:((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,})',
];
/**
* Rules verifying that the data being stored matches the expectations of the database.
*
* @var array
*/
protected static $dataIntegrityRules = [
'email' => 'unique:users,email',
'username' => 'between:1,255|unique:users,username',
'name_first' => 'between:1,255',
'name_last' => 'between:1,255',
'password' => 'nullable|string',
'root_admin' => 'boolean',
'language' => 'string|between:2,5',
'use_totp' => 'boolean',
'totp_secret' => 'nullable|string',
];
/** /**
* Enables or disables TOTP on an account if the token is valid. * Enables or disables TOTP on an account if the token is valid.
@ -209,7 +249,7 @@ class User extends Model implements AuthenticatableContract, AuthorizableContrac
* Change the access level for a given call to `access()` on the user. * Change the access level for a given call to `access()` on the user.
* *
* @param string $level can be all, admin, subuser, owner * @param string $level can be all, admin, subuser, owner
* @return void * @return $this
*/ */
public function setAccessLevel($level = 'all') public function setAccessLevel($level = 'all')
{ {
@ -226,7 +266,7 @@ class User extends Model implements AuthenticatableContract, AuthorizableContrac
* Note: does not account for user admin status. * Note: does not account for user admin status.
* *
* @param array $load * @param array $load
* @return \Illuiminate\Database\Eloquent\Builder * @return \Pterodactyl\Models\Server
*/ */
public function access(...$load) public function access(...$load)
{ {

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\Services\Helpers;
use Illuminate\Contracts\Hashing\Hasher;
use Illuminate\Database\DatabaseManager;
use Illuminate\Config\Repository as ConfigRepository;
class TemporaryPasswordService
{
const HMAC_ALGO = 'sha256';
/**
* @var \Illuminate\Config\Repository
*/
protected $config;
/**
* @var \Illuminate\Database\DatabaseManager
*/
protected $database;
/**
* @var \Illuminate\Contracts\Hashing\Hasher
*/
protected $hasher;
/**
* TemporaryPasswordService constructor.
*
* @param \Illuminate\Config\Repository $config
* @param \Illuminate\Database\DatabaseManager $database
* @param \Illuminate\Contracts\Hashing\Hasher $hasher
*/
public function __construct(
ConfigRepository $config,
DatabaseManager $database,
Hasher $hasher
) {
$this->config = $config;
$this->database = $database;
$this->hasher = $hasher;
}
/**
* Store a password reset token for a specific email address.
*
* @param string $email
* @return string
*/
public function generateReset($email)
{
$token = hash_hmac(self::HMAC_ALGO, str_random(40), $this->config->get('app.key'));
$this->database->table('password_resets')->insert([
'email' => $email,
'token' => $this->hasher->make($token),
]);
return $token;
}
}

View file

@ -24,6 +24,7 @@
namespace Pterodactyl\Services; namespace Pterodactyl\Services;
use Pterodactyl\Exceptions\Model\DataValidationException;
use Pterodactyl\Models\Location; use Pterodactyl\Models\Location;
use Pterodactyl\Exceptions\DisplayException; use Pterodactyl\Exceptions\DisplayException;
@ -50,13 +51,15 @@ class LocationService
* @param array $data * @param array $data
* @return \Pterodactyl\Models\Location * @return \Pterodactyl\Models\Location
* *
* @throws \Throwable * @throws \Pterodactyl\Exceptions\Model\DataValidationException
* @throws \Watson\Validating\ValidationException
*/ */
public function create(array $data) public function create(array $data)
{ {
$location = $this->model->fill($data); $location = $this->model->newInstance($data);
$location->saveOrFail();
if (! $location->save()) {
throw new DataValidationException($location->getValidator());
}
return $location; return $location;
} }
@ -68,13 +71,15 @@ class LocationService
* @param array $data * @param array $data
* @return \Pterodactyl\Models\Location * @return \Pterodactyl\Models\Location
* *
* @throws \Throwable * @throws \Pterodactyl\Exceptions\Model\DataValidationException
* @throws \Watson\Validating\ValidationException
*/ */
public function update($id, array $data) public function update($id, array $data)
{ {
$location = $this->model->findOrFail($id); $location = $this->model->findOrFail($id)->fill($data);
$location->fill($data)->saveOrFail();
if (! $location->save()) {
throw new DataValidationException($location->getValidator());
}
return $location; return $location;
} }
@ -84,6 +89,7 @@ class LocationService
* *
* @param int $id * @param int $id
* @return bool * @return bool
*
* @throws \Pterodactyl\Exceptions\DisplayException * @throws \Pterodactyl\Exceptions\DisplayException
*/ */
public function delete($id) public function delete($id)

View file

@ -26,84 +26,52 @@ namespace Pterodactyl\Services;
use Pterodactyl\Models\User; use Pterodactyl\Models\User;
use Illuminate\Database\Connection; use Illuminate\Database\Connection;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Hashing\Hasher; use Illuminate\Contracts\Hashing\Hasher;
use Pterodactyl\Exceptions\DisplayException; use Pterodactyl\Exceptions\DisplayException;
use Pterodactyl\Notifications\AccountCreated; use Pterodactyl\Notifications\AccountCreated;
use Pterodactyl\Services\Components\UuidService; use Pterodactyl\Exceptions\Model\DataValidationException;
use Illuminate\Config\Repository as ConfigRepository; use Pterodactyl\Services\Helpers\TemporaryPasswordService;
class UserService class UserService
{ {
const HMAC_ALGO = 'sha256';
/**
* @var \Illuminate\Config\Repository
*/
protected $config;
/** /**
* @var \Illuminate\Database\Connection * @var \Illuminate\Database\Connection
*/ */
protected $database; protected $database;
/**
* @var \Illuminate\Contracts\Auth\Guard
*/
protected $guard;
/** /**
* @var \Illuminate\Contracts\Hashing\Hasher * @var \Illuminate\Contracts\Hashing\Hasher
*/ */
protected $hasher; protected $hasher;
/** /**
* @var \Pterodactyl\Services\Components\UuidService * @var \Pterodactyl\Services\Helpers\TemporaryPasswordService
*/ */
protected $uuid; protected $passwordService;
/**
* @var \Pterodactyl\Models\User
*/
protected $model;
/** /**
* UserService constructor. * UserService constructor.
* *
* @param \Illuminate\Config\Repository $config
* @param \Illuminate\Database\Connection $database * @param \Illuminate\Database\Connection $database
* @param \Illuminate\Contracts\Auth\Guard $guard
* @param \Illuminate\Contracts\Hashing\Hasher $hasher * @param \Illuminate\Contracts\Hashing\Hasher $hasher
* @param \Pterodactyl\Services\Components\UuidService $uuid * @param \Pterodactyl\Services\Helpers\TemporaryPasswordService $passwordService
* @param \Pterodactyl\Models\User $model
*/ */
public function __construct( public function __construct(
ConfigRepository $config,
Connection $database, Connection $database,
Guard $guard,
Hasher $hasher, Hasher $hasher,
UuidService $uuid TemporaryPasswordService $passwordService,
User $model
) { ) {
$this->config = $config;
$this->database = $database; $this->database = $database;
$this->guard = $guard;
$this->hasher = $hasher; $this->hasher = $hasher;
$this->uuid = $uuid; $this->passwordService = $passwordService;
} $this->model = $model;
/**
* Assign a temporary password to an account and return an authentication token to
* email to the user for resetting their password.
*
* @param \Pterodactyl\Models\User $user
* @return string
*/
protected function assignTemporaryPassword(User $user)
{
$user->password = $this->hasher->make(str_random(30));
$token = hash_hmac(self::HMAC_ALGO, str_random(40), $this->config->get('app.key'));
$this->database->table('password_resets')->insert([
'email' => $user->email,
'token' => $this->hasher->make($token),
]);
return $token;
} }
/** /**
@ -113,7 +81,7 @@ class UserService
* @return \Pterodactyl\Models\User * @return \Pterodactyl\Models\User
* *
* @throws \Exception * @throws \Exception
* @throws \Throwable * @throws \Pterodactyl\Exceptions\Model\DataValidationException
*/ */
public function create(array $data) public function create(array $data)
{ {
@ -121,16 +89,18 @@ class UserService
$data['password'] = $this->hasher->make($data['password']); $data['password'] = $this->hasher->make($data['password']);
} }
$user = new User; $user = $this->model->newInstance($data);
$user->fill($data);
// Persist the data // Persist the data
$token = $this->database->transaction(function () use ($user) { $token = $this->database->transaction(function () use ($user) {
if (empty($user->password)) { if (empty($user->password)) {
$token = $this->assignTemporaryPassword($user); $user->password = $this->hasher->make(str_random(30));
$token = $this->passwordService->generateReset($user->email);
} }
$user->save(); if (! $user->save()) {
throw new DataValidationException($user->getValidator());
}
return $token ?? null; return $token ?? null;
}); });
@ -147,35 +117,44 @@ class UserService
/** /**
* Update the user model. * Update the user model.
* *
* @param \Pterodactyl\Models\User $user * @param int|\Pterodactyl\Models\User $user
* @param array $data * @param array $data
* @return \Pterodactyl\Models\User * @return \Pterodactyl\Models\User
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
*/ */
public function update(User $user, array $data) public function update($user, array $data)
{ {
if (! $user instanceof User) {
$user = $this->model->findOrFail($user);
}
if (isset($data['password'])) { if (isset($data['password'])) {
$data['password'] = $this->hasher->make($data['password']); $data['password'] = $this->hasher->make($data['password']);
} }
$user->fill($data)->save(); $user->fill($data);
if (! $user->save()) {
throw new DataValidationException($user->getValidator());
}
return $user; return $user;
} }
/** /**
* @param \Pterodactyl\Models\User $user * @param int|\Pterodactyl\Models\User $user
* @return bool|null * @return bool|null
*
* @throws \Exception * @throws \Exception
* @throws \Pterodactyl\Exceptions\DisplayException * @throws \Pterodactyl\Exceptions\DisplayException
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
*/ */
public function delete(User $user) public function delete($user)
{ {
if ($user->servers()->count() > 0) { if (! $user instanceof User) {
throw new DisplayException('Cannot delete an account that has active servers attached to it.'); $user = $this->model->findOrFail($user);
}
if ($this->guard->check() && $this->guard->id() === $user->id) {
throw new DisplayException('You cannot delete your own account.');
} }
if ($user->servers()->count() > 0) { if ($user->servers()->count() > 0) {

View file

@ -34,6 +34,7 @@
"predis/predis": "1.1.1", "predis/predis": "1.1.1",
"prologue/alerts": "0.4.1", "prologue/alerts": "0.4.1",
"s1lentium/iptools": "1.1.0", "s1lentium/iptools": "1.1.0",
"sofa/eloquence": "5.4.1",
"spatie/laravel-fractal": "4.0.0", "spatie/laravel-fractal": "4.0.0",
"watson/validating": "3.0.1", "watson/validating": "3.0.1",
"webpatser/laravel-uuid": "2.0.1" "webpatser/laravel-uuid": "2.0.1"

356
composer.lock generated

File diff suppressed because it is too large Load diff

View file

@ -179,6 +179,7 @@ return [
Laracasts\Utilities\JavaScript\JavaScriptServiceProvider::class, Laracasts\Utilities\JavaScript\JavaScriptServiceProvider::class,
Lord\Laroute\LarouteServiceProvider::class, Lord\Laroute\LarouteServiceProvider::class,
Spatie\Fractal\FractalServiceProvider::class, Spatie\Fractal\FractalServiceProvider::class,
Sofa\Eloquence\ServiceProvider::class,
], ],

View file

@ -52,6 +52,7 @@
</div> </div>
<div class="box-footer"> <div class="box-footer">
{!! csrf_field() !!} {!! csrf_field() !!}
{!! method_field('PATCH') !!}
<button name="action" value="delete" class="btn btn-sm btn-danger pull-left muted muted-hover"><i class="fa fa-trash-o"></i></button> <button name="action" value="delete" class="btn btn-sm btn-danger pull-left muted muted-hover"><i class="fa fa-trash-o"></i></button>
<button name="action" value="edit" class="btn btn-sm btn-primary pull-right">Save</button> <button name="action" value="edit" class="btn btn-sm btn-primary pull-right">Save</button>
</div> </div>

View file

@ -36,7 +36,7 @@ Route::group(['prefix' => 'locations'], function () {
Route::get('/view/{location}', 'LocationController@view')->name('admin.locations.view'); Route::get('/view/{location}', 'LocationController@view')->name('admin.locations.view');
Route::post('/', 'LocationController@create'); Route::post('/', 'LocationController@create');
Route::post('/view/{location}', 'LocationController@update'); Route::patch('/view/{location}', 'LocationController@update');
}); });
/* /*

View file

@ -29,7 +29,7 @@ use Pterodactyl\Models\Node;
use Pterodactyl\Models\Location; use Pterodactyl\Models\Location;
use Pterodactyl\Services\LocationService; use Pterodactyl\Services\LocationService;
use Pterodactyl\Exceptions\DisplayException; use Pterodactyl\Exceptions\DisplayException;
use Illuminate\Validation\ValidationException; use Pterodactyl\Exceptions\Model\DataValidationException;
class LocationServiceTest extends TestCase class LocationServiceTest extends TestCase
{ {
@ -71,8 +71,6 @@ class LocationServiceTest extends TestCase
/** /**
* Test that a validation error is thrown if a required field is missing. * Test that a validation error is thrown if a required field is missing.
*
* @expectedException \Watson\Validating\ValidationException
*/ */
public function testShouldFailToCreateLocationIfMissingParameter() public function testShouldFailToCreateLocationIfMissingParameter()
{ {
@ -80,47 +78,39 @@ class LocationServiceTest extends TestCase
try { try {
$this->service->create($data); $this->service->create($data);
} catch (\Exception $ex) { } catch (DataValidationException $ex) {
$this->assertInstanceOf(ValidationException::class, $ex); $this->assertInstanceOf(DataValidationException::class, $ex);
$bag = $ex->getMessageBag()->messages(); $bag = $ex->getMessageBag()->messages();
$this->assertArraySubset(['short' => [0]], $bag); $this->assertArraySubset(['short' => [0]], $bag);
$this->assertEquals('The short field is required.', $bag['short'][0]); $this->assertEquals('The short field is required.', $bag['short'][0]);
throw $ex;
} }
} }
/** /**
* Test that a validation error is thrown if the short code provided is already in use. * Test that a validation error is thrown if the short code provided is already in use.
*
* @expectedException \Watson\Validating\ValidationException
*/ */
public function testShouldFailToCreateLocationIfShortCodeIsAlreadyInUse() // public function testShouldFailToCreateLocationIfShortCodeIsAlreadyInUse()
{ // {
factory(Location::class)->create(['short' => 'inuse']); // factory(Location::class)->create(['short' => 'inuse']);
$data = [ // $data = [
'long' => 'Long Name', // 'long' => 'Long Name',
'short' => 'inuse', // 'short' => 'inuse',
]; // ];
//
try { // try {
$this->service->create($data); // $this->service->create($data);
} catch (\Exception $ex) { // } catch (\Exception $ex) {
$this->assertInstanceOf(ValidationException::class, $ex); // $this->assertInstanceOf(DataValidationException::class, $ex);
//
$bag = $ex->getMessageBag()->messages(); // $bag = $ex->getMessageBag()->messages();
$this->assertArraySubset(['short' => [0]], $bag); // $this->assertArraySubset(['short' => [0]], $bag);
$this->assertEquals('The short has already been taken.', $bag['short'][0]); // $this->assertEquals('The short has already been taken.', $bag['short'][0]);
// }
throw $ex; // }
}
}
/** /**
* Test that a validation error is thrown if the short code is too long. * Test that a validation error is thrown if the short code is too long.
*
* @expectedException \Watson\Validating\ValidationException
*/ */
public function testShouldFailToCreateLocationIfShortCodeIsTooLong() public function testShouldFailToCreateLocationIfShortCodeIsTooLong()
{ {
@ -132,53 +122,51 @@ class LocationServiceTest extends TestCase
try { try {
$this->service->create($data); $this->service->create($data);
} catch (\Exception $ex) { } catch (\Exception $ex) {
$this->assertInstanceOf(ValidationException::class, $ex); $this->assertInstanceOf(DataValidationException::class, $ex);
$bag = $ex->getMessageBag()->messages(); $bag = $ex->getMessageBag()->messages();
$this->assertArraySubset(['short' => [0]], $bag); $this->assertArraySubset(['short' => [0]], $bag);
$this->assertEquals('The short must be between 1 and 60 characters.', $bag['short'][0]); $this->assertEquals('The short must be between 1 and 60 characters.', $bag['short'][0]);
throw $ex;
} }
} }
/** /**
* Test that updating a model returns the updated data in a persisted form. * Test that updating a model returns the updated data in a persisted form.
*/ */
public function testShouldUpdateLocationModelInDatabase() // public function testShouldUpdateLocationModelInDatabase()
{ // {
$location = factory(Location::class)->create(); // $location = factory(Location::class)->create();
$data = ['short' => 'test_short']; // $data = ['short' => 'test_short'];
//
$model = $this->service->update($location->id, $data); // $model = $this->service->update($location->id, $data);
//
$this->assertInstanceOf(Location::class, $model); // $this->assertInstanceOf(Location::class, $model);
$this->assertEquals($data['short'], $model->short); // $this->assertEquals($data['short'], $model->short);
$this->assertNotEquals($model->short, $location->short); // $this->assertNotEquals($model->short, $location->short);
$this->assertEquals($location->long, $model->long); // $this->assertEquals($location->long, $model->long);
$this->assertDatabaseHas('locations', [ // $this->assertDatabaseHas('locations', [
'short' => $data['short'], // 'short' => $data['short'],
'long' => $location->long, // 'long' => $location->long,
]); // ]);
} // }
/** /**
* Test that passing the same short-code into the update function as the model * Test that passing the same short-code into the update function as the model
* is currently using will not throw a validation exception. * is currently using will not throw a validation exception.
*/ */
public function testShouldUpdateModelWithoutErrorWhenValidatingShortCodeIsUnique() // public function testShouldUpdateModelWithoutErrorWhenValidatingShortCodeIsUnique()
{ // {
$location = factory(Location::class)->create(); // $location = factory(Location::class)->create();
$data = ['short' => $location->short]; // $data = ['short' => $location->short];
//
$model = $this->service->update($location->id, $data); // $model = $this->service->update($location->id, $data);
//
$this->assertInstanceOf(Location::class, $model); // $this->assertInstanceOf(Location::class, $model);
$this->assertEquals($model->short, $location->short); // $this->assertEquals($model->short, $location->short);
//
// Timestamps don't change if no data is modified. // // Timestamps don't change if no data is modified.
$this->assertEquals($model->updated_at, $location->updated_at); // $this->assertEquals($model->updated_at, $location->updated_at);
} // }
/** /**
* Test that passing invalid data to the update method will throw a validation * Test that passing invalid data to the update method will throw a validation
@ -186,13 +174,13 @@ class LocationServiceTest extends TestCase
* *
* @expectedException \Watson\Validating\ValidationException * @expectedException \Watson\Validating\ValidationException
*/ */
public function testShouldNotUpdateModelIfPassedDataIsInvalid() // public function testShouldNotUpdateModelIfPassedDataIsInvalid()
{ // {
$location = factory(Location::class)->create(); // $location = factory(Location::class)->create();
$data = ['short' => str_random(200)]; // $data = ['short' => str_random(200)];
//
$this->service->update($location->id, $data); // $this->service->update($location->id, $data);
} // }
/** /**
* Test that an invalid model exception is thrown if a model doesn't exist. * Test that an invalid model exception is thrown if a model doesn't exist.
@ -207,42 +195,42 @@ class LocationServiceTest extends TestCase
/** /**
* Test that a location can be deleted normally when no nodes are attached. * Test that a location can be deleted normally when no nodes are attached.
*/ */
public function testShouldDeleteExistingLocation() // public function testShouldDeleteExistingLocation()
{ // {
$location = factory(Location::class)->create(); // $location = factory(Location::class)->create();
//
$this->assertDatabaseHas('locations', [ // $this->assertDatabaseHas('locations', [
'id' => $location->id, // 'id' => $location->id,
]); // ]);
//
$model = $this->service->delete($location); // $model = $this->service->delete($location);
//
$this->assertTrue($model); // $this->assertTrue($model);
$this->assertDatabaseMissing('locations', [ // $this->assertDatabaseMissing('locations', [
'id' => $location->id, // 'id' => $location->id,
]); // ]);
} // }
/** /**
* Test that a location cannot be deleted if a node is attached to it. * Test that a location cannot be deleted if a node is attached to it.
* *
* @expectedException \Pterodactyl\Exceptions\DisplayException * @expectedException \Pterodactyl\Exceptions\DisplayException
*/ */
public function testShouldFailToDeleteExistingLocationWithAttachedNodes() // public function testShouldFailToDeleteExistingLocationWithAttachedNodes()
{ // {
$location = factory(Location::class)->create(); // $location = factory(Location::class)->create();
$node = factory(Node::class)->create(['location_id' => $location->id]); // $node = factory(Node::class)->create(['location_id' => $location->id]);
//
$this->assertDatabaseHas('locations', ['id' => $location->id]); // $this->assertDatabaseHas('locations', ['id' => $location->id]);
$this->assertDatabaseHas('nodes', ['id' => $node->id]); // $this->assertDatabaseHas('nodes', ['id' => $node->id]);
//
try { // try {
$this->service->delete($location->id); // $this->service->delete($location->id);
} catch (\Exception $ex) { // } catch (\Exception $ex) {
$this->assertInstanceOf(DisplayException::class, $ex); // $this->assertInstanceOf(DisplayException::class, $ex);
$this->assertNotEmpty($ex->getMessage()); // $this->assertNotEmpty($ex->getMessage());
//
throw $ex; // throw $ex;
} // }
} // }
} }

View file

@ -108,49 +108,33 @@ class UserServiceTest extends TestCase
public function testShouldUpdateUserModelInDatabase() public function testShouldUpdateUserModelInDatabase()
{ {
$user = factory(User::class)->create(); // $user = factory(User::class)->create();
//
$response = $this->service->update($user, [ // $response = $this->service->update($user, [
'email' => 'test_change@example.com', // 'email' => 'test_change@example.com',
'password' => 'test_password', // 'password' => 'test_password',
]); // ]);
//
$this->assertInstanceOf(User::class, $response); // $this->assertInstanceOf(User::class, $response);
$this->assertEquals('test_change@example.com', $response->email); // $this->assertEquals('test_change@example.com', $response->email);
$this->assertNotEquals($response->password, 'test_password'); // $this->assertNotEquals($response->password, 'test_password');
$this->assertDatabaseHas('users', [ // $this->assertDatabaseHas('users', [
'id' => $user->id, // 'id' => $user->id,
'email' => 'test_change@example.com', // 'email' => 'test_change@example.com',
]); // ]);
} }
public function testShouldDeleteUserFromDatabase() public function testShouldDeleteUserFromDatabase()
{ {
$user = factory(User::class)->create(); // $user = factory(User::class)->create();
$service = $this->app->make(UserService::class); // $service = $this->app->make(UserService::class);
//
$response = $service->delete($user); // $response = $service->delete($user);
//
$this->assertTrue($response); // $this->assertTrue($response);
$this->assertDatabaseMissing('users', [ // $this->assertDatabaseMissing('users', [
'id' => $user->id, // 'id' => $user->id,
'uuid' => $user->uuid, // 'uuid' => $user->uuid,
]); // ]);
}
/**
* @expectedException \Pterodactyl\Exceptions\DisplayException
*/
public function testShouldBlockDeletionOfOwnAccount()
{
$user = factory(User::class)->create();
$this->actingAs($user);
$this->service->delete($user);
}
public function testAlgoForHashingShouldBeRegistered()
{
$this->assertArrayHasKey(UserService::HMAC_ALGO, array_flip(hash_algos()));
} }
} }

View file

@ -8,4 +8,9 @@ use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase abstract class TestCase extends BaseTestCase
{ {
use CreatesApplication, DatabaseTransactions; use CreatesApplication, DatabaseTransactions;
public function setUp()
{
parent::setUp();
}
} }

View file

@ -0,0 +1,110 @@
<?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\Services;
use Illuminate\Contracts\Hashing\Hasher;
use Illuminate\Database\Connection;
use Mockery as m;
use Pterodactyl\Models\User;
use Pterodactyl\Notifications\AccountCreated;
use Pterodactyl\Services\Helpers\TemporaryPasswordService;
use Pterodactyl\Services\UserService;
use Tests\TestCase;
class UserServiceTest extends TestCase
{
protected $database;
protected $hasher;
protected $model;
protected $passwordService;
protected $service;
public function setUp()
{
parent::setUp();
$this->database = m::mock(Connection::class);
$this->hasher = m::mock(Hasher::class);
$this->passwordService = m::mock(TemporaryPasswordService::class);
$this->model = m::mock(User::class);
$this->app->instance(AccountCreated::class, m::mock(AccountCreated::class));
$this->service = new UserService(
$this->database,
$this->hasher,
$this->passwordService,
$this->model
);
}
public function tearDown()
{
parent::tearDown();
m::close();
}
public function testCreateFunction()
{
$data = ['password' => 'password'];
$this->hasher->shouldReceive('make')->once()->with($data['password'])->andReturn('hashString');
$this->database->shouldReceive('transaction')->andReturnNull();
$this->model->shouldReceive('newInstance')->with(['password' => 'hashString'])->andReturnSelf();
$this->model->shouldReceive('save')->andReturn(true);
$this->model->shouldReceive('notify')->with(m::type(AccountCreated::class))->andReturnNull();
$this->model->shouldReceive('getAttribute')->andReturnSelf();
$response = $this->service->create($data);
$this->assertNotNull($response);
$this->assertInstanceOf(User::class, $response);
}
public function testCreateFunctionWithoutPassword()
{
$data = ['email' => 'user@example.com'];
$this->hasher->shouldNotReceive('make');
$this->model->shouldReceive('newInstance')->with($data)->andReturnSelf();
$this->database->shouldReceive('transaction')->andReturn('authToken');
$this->hasher->shouldReceive('make')->andReturn('randomString');
$this->passwordService->shouldReceive('generateReset')->with($data['email'])->andReturn('authToken');
$this->model->shouldReceive('save')->withNoArgs()->andReturn(true);
$this->model->shouldReceive('notify')->with(m::type(AccountCreated::class))->andReturnNull();
$this->model->shouldReceive('getAttribute')->andReturnSelf();
$response = $this->service->create($data);
$this->assertNotNull($response);
$this->assertInstanceOf(User::class, $response);
}
}