Update user service to be more separated

This commit is contained in:
Dane Everitt 2017-08-04 19:11:41 -05:00
parent 8daec38622
commit 275c01bc37
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
12 changed files with 473 additions and 1361 deletions

View file

@ -35,16 +35,6 @@ interface UserRepositoryInterface extends RepositoryInterface, SearchableInterfa
*/
public function getAllUsersWithCounts();
/**
* Delete a user if they have no servers attached to their account.
*
* @param int $id
* @return bool
*
* @throws \Pterodactyl\Exceptions\DisplayException
*/
public function deleteIfNoServers($id);
/**
* Return all matching models for a user in a format that can be used for dropdowns.
*

View file

@ -25,13 +25,16 @@
namespace Pterodactyl\Http\Controllers\Admin;
use Illuminate\Http\Request;
use Pterodactyl\Contracts\Repository\UserRepositoryInterface;
use Pterodactyl\Models\User;
use Prologue\Alerts\AlertsMessageBag;
use Pterodactyl\Services\UserService;
use Pterodactyl\Exceptions\DisplayException;
use Pterodactyl\Http\Controllers\Controller;
use Pterodactyl\Services\Users\UpdateService;
use Pterodactyl\Services\Users\CreationService;
use Pterodactyl\Services\Users\DeletionService;
use Illuminate\Contracts\Translation\Translator;
use Pterodactyl\Http\Requests\Admin\UserFormRequest;
use Pterodactyl\Contracts\Repository\UserRepositoryInterface;
class UserController extends Controller
{
@ -41,53 +44,67 @@ class UserController extends Controller
protected $alert;
/**
* @var \Pterodactyl\Services\UserService
* @var \Pterodactyl\Services\Users\CreationService
*/
protected $service;
protected $creationService;
/**
* @var \Pterodactyl\Models\User
* @var \Pterodactyl\Services\Users\DeletionService
*/
protected $model;
protected $deletionService;
/**
* @var \Pterodactyl\Contracts\Repository\UserRepositoryInterface
*/
protected $repository;
/**
* @var \Illuminate\Contracts\Translation\Translator
*/
protected $translator;
/**
* @var \Pterodactyl\Services\Users\UpdateService
*/
protected $updateService;
/**
* UserController constructor.
*
* @param \Prologue\Alerts\AlertsMessageBag $alert
* @param \Pterodactyl\Services\UserService $service
* @param \Pterodactyl\Services\Users\CreationService $creationService
* @param \Pterodactyl\Services\Users\DeletionService $deletionService
* @param \Illuminate\Contracts\Translation\Translator $translator
* @param \Pterodactyl\Services\Users\UpdateService $updateService
* @param \Pterodactyl\Contracts\Repository\UserRepositoryInterface $repository
* @param \Pterodactyl\Models\User $model
*/
public function __construct(
AlertsMessageBag $alert,
UserService $service,
UserRepositoryInterface $repository,
User $model
CreationService $creationService,
DeletionService $deletionService,
Translator $translator,
UpdateService $updateService,
UserRepositoryInterface $repository
) {
$this->alert = $alert;
$this->service = $service;
$this->model = $model;
$this->creationService = $creationService;
$this->deletionService = $deletionService;
$this->repository = $repository;
$this->translator = $translator;
$this->updateService = $updateService;
}
/**
* Display user index page.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Http\Request $request
* @return \Illuminate\View\View
*/
public function index(Request $request)
{
$users = $this->repository->search($request->input('query'))->getAllUsersWithCounts();
return view('admin.users.index', [
'users' => $users,
]);
return view('admin.users.index', ['users' => $users]);
}
/**
@ -103,21 +120,19 @@ class UserController extends Controller
/**
* Display user view page.
*
* @param \Pterodactyl\Models\User $user
* @param \Pterodactyl\Models\User $user
* @return \Illuminate\View\View
*/
public function view(User $user)
{
return view('admin.users.view', [
'user' => $user,
]);
return view('admin.users.view', ['user' => $user]);
}
/**
* Delete a user from the system.
*
* @param \Illuminate\Http\Request $request
* @param \Pterodactyl\Models\User $user
* @param \Illuminate\Http\Request $request
* @param \Pterodactyl\Models\User $user
* @return \Illuminate\Http\RedirectResponse
*
* @throws \Exception
@ -126,16 +141,10 @@ class UserController extends Controller
public function delete(Request $request, User $user)
{
if ($request->user()->id === $user->id) {
throw new DisplayException('Cannot delete your own account.');
throw new DisplayException($this->translator->trans('admin/user.exceptions.user_has_servers'));
}
try {
$this->repository->deleteIfNoServers($user->id);
return redirect()->route('admin.users');
} catch (DisplayException $ex) {
$this->alert->danger($ex->getMessage())->flash();
}
$this->deletionService->handle($user);
return redirect()->route('admin.users.view', $user->id);
}
@ -143,7 +152,7 @@ class UserController extends Controller
/**
* Create a user.
*
* @param \Pterodactyl\Http\Requests\Admin\UserFormRequest $request
* @param \Pterodactyl\Http\Requests\Admin\UserFormRequest $request
* @return \Illuminate\Http\RedirectResponse
*
* @throws \Exception
@ -151,9 +160,8 @@ class UserController extends Controller
*/
public function store(UserFormRequest $request)
{
$user = $this->service->create($request->normalize());
$this->alert->success('Account has been successfully created.')->flash();
$user = $this->creationService->handle($request->normalize());
$this->alert->success($this->translator->trans('admin/user.notices.account_created'))->flash();
return redirect()->route('admin.users.view', $user->id);
}
@ -169,8 +177,8 @@ class UserController extends Controller
*/
public function update(UserFormRequest $request, User $user)
{
$this->service->update($user->id, $request->normalize());
$this->alert->success('User account has been updated.')->flash();
$this->updateService->handle($user->id, $request->normalize());
$this->alert->success($this->translator->trans('admin/user.notices.account_updated'))->flash();
return redirect()->route('admin.users.view', $user->id);
}

View file

@ -27,8 +27,6 @@ namespace Pterodactyl\Repositories\Eloquent;
use Illuminate\Contracts\Config\Repository as ConfigRepository;
use Illuminate\Foundation\Application;
use Pterodactyl\Contracts\Repository\UserRepositoryInterface;
use Pterodactyl\Exceptions\DisplayException;
use Pterodactyl\Exceptions\Repository\RecordNotFoundException;
use Pterodactyl\Models\User;
use Pterodactyl\Repositories\Eloquent\Attributes\SearchableRepository;
@ -76,24 +74,6 @@ class UserRepository extends SearchableRepository implements UserRepositoryInter
);
}
/**
* {@inheritdoc}
*/
public function deleteIfNoServers($id)
{
$user = $this->getBuilder()->withCount('servers')->where('id', $id)->first();
if (! $user) {
throw new RecordNotFoundException();
}
if ($user->servers_count > 0) {
throw new DisplayException('Cannot delete an account that has active servers attached to it.');
}
return $user->delete();
}
/**
* {@inheritdoc}
*/

File diff suppressed because it is too large Load diff

View file

@ -1,182 +0,0 @@
<?php
/**
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>
* Some Modifications (c) 2015 Dylan Seidt <dylan.seidt@gmail.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\Repositories;
use DB;
use Auth;
use Hash;
use Settings;
use Validator;
use Pterodactyl\Models;
use Pterodactyl\Services\UuidService;
use Pterodactyl\Exceptions\DisplayException;
use Pterodactyl\Exceptions\DisplayValidationException;
class old_UserRepository
{
/**
* Creates a user on the panel. Returns the created user's ID.
*
* @param array $data
* @return \Pterodactyl\Models\User
*
* @throws \Pterodactyl\Exceptions\DisplayValidationException
*/
public function create(array $data)
{
$validator = Validator::make($data, [
'email' => 'required|email|unique:users,email',
'username' => 'required|string|between:1,255|unique:users,username|' . Models\User::USERNAME_RULES,
'name_first' => 'required|string|between:1,255',
'name_last' => 'required|string|between:1,255',
'password' => 'sometimes|nullable|' . Models\User::PASSWORD_RULES,
'root_admin' => 'required|boolean',
'custom_id' => 'sometimes|nullable|unique:users,id',
]);
// Run validator, throw catchable and displayable exception if it fails.
// Exception includes a JSON result of failed validation rules.
if ($validator->fails()) {
throw new DisplayValidationException(json_encode($validator->errors()));
}
DB::beginTransaction();
try {
$user = new Models\User;
$uuid = new UuidService;
// Support for API Services
if (isset($data['custom_id']) && ! is_null($data['custom_id'])) {
$user->id = $token;
}
// UUIDs are not mass-fillable.
$user->uuid = $uuid->generate('users', 'uuid');
$user->fill([
'email' => $data['email'],
'username' => $data['username'],
'name_first' => $data['name_first'],
'name_last' => $data['name_last'],
'password' => (empty($data['password'])) ? 'unset' : Hash::make($data['password']),
'root_admin' => $data['root_admin'],
'language' => Settings::get('default_language', 'en'),
]);
$user->save();
DB::commit();
return $user;
} catch (\Exception $ex) {
DB::rollBack();
throw $ex;
}
}
/**
* Updates a user on the panel.
*
* @param int $id
* @param array $data
* @return \Pterodactyl\Models\User
*
* @throws \Pterodactyl\Exceptions\DisplayValidationException
*/
public function update($id, array $data)
{
$user = Models\User::findOrFail($id);
$validator = Validator::make($data, [
'email' => 'sometimes|required|email|unique:users,email,' . $id,
'username' => 'sometimes|required|string|between:1,255|unique:users,username,' . $user->id . '|' . Models\User::USERNAME_RULES,
'name_first' => 'sometimes|required|string|between:1,255',
'name_last' => 'sometimes|required|string|between:1,255',
'password' => 'sometimes|nullable|' . Models\User::PASSWORD_RULES,
'root_admin' => 'sometimes|required|boolean',
'language' => 'sometimes|required|string|min:1|max:5',
'use_totp' => 'sometimes|required|boolean',
'totp_secret' => 'sometimes|required|size:16',
]);
// Run validator, throw catchable and displayable exception if it fails.
// Exception includes a JSON result of failed validation rules.
if ($validator->fails()) {
throw new DisplayValidationException(json_encode($validator->errors()));
}
// The password and root_admin fields are not mass assignable.
if (! empty($data['password'])) {
$data['password'] = Hash::make($data['password']);
} else {
unset($data['password']);
}
$user->fill($data)->save();
return $user;
}
/**
* Deletes a user on the panel.
*
* @param int $id
* @return void
* @todo Move user self-deletion checking to the controller, rather than the repository.
*
* @throws \Pterodactyl\Exceptions\DisplayException
*/
public function delete($id)
{
$user = Models\User::findOrFail($id);
if (Models\Server::where('owner_id', $id)->count() > 0) {
throw new DisplayException('Cannot delete a user with active servers attached to thier account.');
}
if (! is_null(Auth::user()) && (int) Auth::user()->id === (int) $id) {
throw new DisplayException('Cannot delete your own account.');
}
DB::beginTransaction();
try {
foreach (Models\Subuser::with('permissions')->where('user_id', $id)->get() as &$subuser) {
foreach ($subuser->permissions as &$permission) {
$permission->delete();
}
$subuser->delete();
}
$user->delete();
DB::commit();
} catch (\Exception $ex) {
DB::rollBack();
throw $ex;
}
}
}

View file

@ -22,7 +22,7 @@
* SOFTWARE.
*/
namespace Pterodactyl\Services;
namespace Pterodactyl\Services\Users;
use Illuminate\Foundation\Application;
use Illuminate\Contracts\Hashing\Hasher;
@ -32,7 +32,7 @@ use Pterodactyl\Notifications\AccountCreated;
use Pterodactyl\Services\Helpers\TemporaryPasswordService;
use Pterodactyl\Contracts\Repository\UserRepositoryInterface;
class UserService
class CreationService
{
/**
* @var \Illuminate\Foundation\Application
@ -40,9 +40,9 @@ class UserService
protected $app;
/**
* @var \Illuminate\Database\Connection
* @var \Illuminate\Database\ConnectionInterface
*/
protected $database;
protected $connection;
/**
* @var \Illuminate\Contracts\Hashing\Hasher
@ -65,25 +65,25 @@ class UserService
protected $repository;
/**
* UserService constructor.
* CreationService constructor.
*
* @param \Illuminate\Foundation\Application $application
* @param \Illuminate\Notifications\ChannelManager $notification
* @param \Illuminate\Database\ConnectionInterface $database
* @param \Illuminate\Contracts\Hashing\Hasher $hasher
* @param \Pterodactyl\Services\Helpers\TemporaryPasswordService $passwordService
* @param \Pterodactyl\Contracts\Repository\UserRepositoryInterface $repository
* @param \Illuminate\Foundation\Application $application
* @param \Illuminate\Notifications\ChannelManager $notification
* @param \Illuminate\Database\ConnectionInterface $connection
* @param \Illuminate\Contracts\Hashing\Hasher $hasher
* @param \Pterodactyl\Services\Helpers\TemporaryPasswordService $passwordService
* @param \Pterodactyl\Contracts\Repository\UserRepositoryInterface $repository
*/
public function __construct(
Application $application,
ChannelManager $notification,
ConnectionInterface $database,
ConnectionInterface $connection,
Hasher $hasher,
TemporaryPasswordService $passwordService,
UserRepositoryInterface $repository
) {
$this->app = $application;
$this->database = $database;
$this->connection = $connection;
$this->hasher = $hasher;
$this->notification = $notification;
$this->passwordService = $passwordService;
@ -99,25 +99,22 @@ class UserService
* @throws \Exception
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
*/
public function create(array $data)
public function handle(array $data)
{
if (array_key_exists('password', $data) && ! empty($data['password'])) {
$data['password'] = $this->hasher->make($data['password']);
}
// Begin Transaction
$this->database->beginTransaction();
$this->connection->beginTransaction();
if (! isset($data['password']) || empty($data['password'])) {
$data['password'] = $this->hasher->make(str_random(30));
$token = $this->passwordService->generateReset($data['email']);
}
$user = $this->repository->create($data);
$this->connection->commit();
// Persist the data
$this->database->commit();
// @todo fire event, handle notification there
$this->notification->send($user, $this->app->makeWith(AccountCreated::class, [
'user' => [
'name' => $user->name_first,
@ -128,24 +125,4 @@ class UserService
return $user;
}
/**
* Update the user model instance.
*
* @param int $id
* @param array $data
* @return mixed
*
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
*/
public function update($id, array $data)
{
if (isset($data['password'])) {
$data['password'] = $this->hasher->make($data['password']);
}
$user = $this->repository->update($id, $data);
return $user;
}
}

View file

@ -0,0 +1,88 @@
<?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\Users;
use Illuminate\Contracts\Translation\Translator;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
use Pterodactyl\Contracts\Repository\UserRepositoryInterface;
use Pterodactyl\Exceptions\DisplayException;
use Pterodactyl\Models\User;
class DeletionService
{
/**
* @var \Pterodactyl\Contracts\Repository\UserRepositoryInterface
*/
protected $repository;
/**
* @var \Illuminate\Contracts\Translation\Translator
*/
protected $translator;
/**
* @var \Pterodactyl\Contracts\Repository\ServerRepositoryInterface
*/
protected $serverRepository;
/**
* DeletionService constructor.
*
* @param \Pterodactyl\Contracts\Repository\ServerRepositoryInterface $serverRepository
* @param \Illuminate\Contracts\Translation\Translator $translator
* @param \Pterodactyl\Contracts\Repository\UserRepositoryInterface $repository
*/
public function __construct(
ServerRepositoryInterface $serverRepository,
Translator $translator,
UserRepositoryInterface $repository
) {
$this->repository = $repository;
$this->translator = $translator;
$this->serverRepository = $serverRepository;
}
/**
* Delete a user from the panel only if they have no servers attached to their account.
*
* @param int|\Pterodactyl\Models\User $user
* @return bool|null
*
* @throws \Pterodactyl\Exceptions\DisplayException
*/
public function handle($user)
{
if (! $user instanceof User) {
$user = $this->repository->find($user);
}
$servers = $this->serverRepository->findWhere([['owner_id', '=', $user->id]]);
if (count($servers) > 0) {
throw new DisplayException($this->translator->trans('admin/user.exceptions.user_has_servers'));
}
return $this->repository->delete($user->id);
}
}

View file

@ -0,0 +1,75 @@
<?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\Users;
use Illuminate\Contracts\Hashing\Hasher;
use Pterodactyl\Contracts\Repository\UserRepositoryInterface;
class UpdateService
{
/**
* @var \Illuminate\Contracts\Hashing\Hasher
*/
protected $hasher;
/**
* @var \Pterodactyl\Contracts\Repository\UserRepositoryInterface
*/
protected $repository;
/**
* UpdateService constructor.
*
* @param \Illuminate\Contracts\Hashing\Hasher $hasher
* @param \Pterodactyl\Contracts\Repository\UserRepositoryInterface $repository
*/
public function __construct(
Hasher $hasher,
UserRepositoryInterface $repository
) {
$this->hasher = $hasher;
$this->repository = $repository;
}
/**
* Update the user model instance.
*
* @param int $id
* @param array $data
* @return mixed
*
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
*/
public function handle($id, array $data)
{
if (isset($data['password'])) {
$data['password'] = $this->hasher->make($data['password']);
}
$user = $this->repository->update($id, $data);
return $user;
}
}