Merge branch 'develop' into pr/1128

This commit is contained in:
Dane Everitt 2018-09-03 15:10:23 -07:00
commit 4d62e4c7b9
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
96 changed files with 1966 additions and 874 deletions

View file

@ -9,7 +9,7 @@
namespace Pterodactyl\Console\Commands\Schedule;
use Carbon\Carbon;
use Cake\Chronos\Chronos;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Pterodactyl\Services\Schedules\ProcessScheduleService;
@ -17,11 +17,6 @@ use Pterodactyl\Contracts\Repository\ScheduleRepositoryInterface;
class ProcessRunnableCommand extends Command
{
/**
* @var \Carbon\Carbon
*/
protected $carbon;
/**
* @var string
*/
@ -45,31 +40,28 @@ class ProcessRunnableCommand extends Command
/**
* ProcessRunnableCommand constructor.
*
* @param \Carbon\Carbon $carbon
* @param \Pterodactyl\Services\Schedules\ProcessScheduleService $processScheduleService
* @param \Pterodactyl\Contracts\Repository\ScheduleRepositoryInterface $repository
*/
public function __construct(
Carbon $carbon,
ProcessScheduleService $processScheduleService,
ScheduleRepositoryInterface $repository
) {
public function __construct(ProcessScheduleService $processScheduleService, ScheduleRepositoryInterface $repository)
{
parent::__construct();
$this->carbon = $carbon;
$this->processScheduleService = $processScheduleService;
$this->repository = $repository;
}
/**
* Handle command execution.
*
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
*/
public function handle()
{
$schedules = $this->repository->getSchedulesToProcess($this->carbon->now()->toAtomString());
$schedules = $this->repository->getSchedulesToProcess(Chronos::now()->toAtomString());
if ($schedules->count() < 1) {
$this->line('There are no scheduled tasks for servers that need to be run.');
return;
}
$bar = $this->output->createProgressBar(count($schedules));
$schedules->each(function ($schedule) use ($bar) {

View file

@ -0,0 +1,15 @@
<?php
namespace Pterodactyl\Contracts\Core;
use Pterodactyl\Events\Event;
interface ReceivesEvents
{
/**
* Handles receiving an event from the application.
*
* @param \Pterodactyl\Events\Event $notification
*/
public function handle(Event $notification): void;
}

View file

@ -202,7 +202,7 @@ interface RepositoryInterface
public function insertIgnore(array $values): bool;
/**
* Get the amount of entries in the database
* Get the amount of entries in the database.
*
* @return int
*/

View file

@ -147,7 +147,7 @@ interface ServerRepositoryInterface extends RepositoryInterface, SearchableInter
public function isUniqueUuidCombo(string $uuid, string $short): bool;
/**
* Get the amount of servers that are suspended
* Get the amount of servers that are suspended.
*
* @return int
*/

View file

@ -0,0 +1,27 @@
<?php
namespace Pterodactyl\Events\Server;
use Pterodactyl\Events\Event;
use Pterodactyl\Models\Server;
use Illuminate\Queue\SerializesModels;
class Installed extends Event
{
use SerializesModels;
/**
* @var \Pterodactyl\Models\Server
*/
public $server;
/**
* Create a new event instance.
*
* @var \Pterodactyl\Models\Server
*/
public function __construct(Server $server)
{
$this->server = $server;
}
}

View file

@ -2,16 +2,14 @@
namespace Pterodactyl\Http\Controllers\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Pterodactyl\Contracts\Repository\AllocationRepositoryInterface;
use Pterodactyl\Contracts\Repository\DatabaseRepositoryInterface;
use Pterodactyl\Contracts\Repository\EggRepositoryInterface;
use Pterodactyl\Contracts\Repository\NodeRepositoryInterface;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
use Pterodactyl\Contracts\Repository\UserRepositoryInterface;
use Pterodactyl\Http\Controllers\Controller;
use Pterodactyl\Contracts\Repository\EggRepositoryInterface;
use Pterodactyl\Traits\Controllers\PlainJavascriptInjection;
use Pterodactyl\Contracts\Repository\NodeRepositoryInterface;
use Pterodactyl\Contracts\Repository\UserRepositoryInterface;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
use Pterodactyl\Contracts\Repository\DatabaseRepositoryInterface;
use Pterodactyl\Contracts\Repository\AllocationRepositoryInterface;
class StatisticsController extends Controller
{
@ -29,15 +27,14 @@ class StatisticsController extends Controller
private $userRepository;
function __construct(
public function __construct(
AllocationRepositoryInterface $allocationRepository,
DatabaseRepositoryInterface $databaseRepository,
EggRepositoryInterface $eggRepository,
NodeRepositoryInterface $nodeRepository,
ServerRepositoryInterface $serverRepository,
UserRepositoryInterface $userRepository
)
{
) {
$this->allocationRepository = $allocationRepository;
$this->databaseRepository = $databaseRepository;
$this->eggRepository = $eggRepository;
@ -83,7 +80,7 @@ class StatisticsController extends Controller
'nodes' => $nodes,
'tokens' => $tokens,
]);
return view('admin.statistics', [
'servers' => $servers,
'nodes' => $nodes,
@ -97,5 +94,4 @@ class StatisticsController extends Controller
'totalAllocations' => $totalAllocations,
]);
}
}

View file

@ -124,7 +124,7 @@ class NodeController extends ApplicationApiController
*/
public function update(UpdateNodeRequest $request): array
{
$node = $this->updateService->returnUpdatedModel()->handle(
$node = $this->updateService->handle(
$request->getModel(Node::class), $request->validated()
);

View file

@ -2,8 +2,14 @@
namespace Pterodactyl\Http\Controllers\Auth;
use Illuminate\Support\Str;
use Prologue\Alerts\AlertsMessageBag;
use Illuminate\Contracts\Hashing\Hasher;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Contracts\Events\Dispatcher;
use Pterodactyl\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Pterodactyl\Contracts\Repository\UserRepositoryInterface;
class ResetPasswordController extends Controller
{
@ -16,6 +22,47 @@ class ResetPasswordController extends Controller
*/
public $redirectTo = '/';
/**
* @var bool
*/
protected $hasTwoFactor = false;
/**
* @var \Prologue\Alerts\AlertsMessageBag
*/
private $alerts;
/**
* @var \Illuminate\Contracts\Events\Dispatcher
*/
private $dispatcher;
/**
* @var \Illuminate\Contracts\Hashing\Hasher
*/
private $hasher;
/**
* @var \Pterodactyl\Contracts\Repository\UserRepositoryInterface
*/
private $userRepository;
/**
* ResetPasswordController constructor.
*
* @param \Prologue\Alerts\AlertsMessageBag $alerts
* @param \Illuminate\Contracts\Events\Dispatcher $dispatcher
* @param \Illuminate\Contracts\Hashing\Hasher $hasher
* @param \Pterodactyl\Contracts\Repository\UserRepositoryInterface $userRepository
*/
public function __construct(AlertsMessageBag $alerts, Dispatcher $dispatcher, Hasher $hasher, UserRepositoryInterface $userRepository)
{
$this->alerts = $alerts;
$this->dispatcher = $dispatcher;
$this->hasher = $hasher;
$this->userRepository = $userRepository;
}
/**
* Return the rules used when validating password reset.
*
@ -29,4 +76,49 @@ class ResetPasswordController extends Controller
'password' => 'required|confirmed|min:8',
];
}
/**
* Reset the given user's password. If the user has two-factor authentication enabled on their
* account do not automatically log them in. In those cases, send the user back to the login
* form with a note telling them their password was changed and to log back in.
*
* @param \Illuminate\Contracts\Auth\CanResetPassword|\Pterodactyl\Models\User $user
* @param string $password
*
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
*/
protected function resetPassword($user, $password)
{
$user = $this->userRepository->update($user->id, [
'password' => $this->hasher->make($password),
$user->getRememberTokenName() => Str::random(60),
]);
$this->dispatcher->dispatch(new PasswordReset($user));
// If the user is not using 2FA log them in, otherwise skip this step and force a
// fresh login where they'll be prompted to enter a token.
if (! $user->use_totp) {
$this->guard()->login($user);
}
$this->hasTwoFactor = $user->use_totp;
}
/**
* Get the response for a successful password reset.
*
* @param string $response
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
*/
protected function sendResetResponse($response)
{
if ($this->hasTwoFactor) {
$this->alerts->success('Your password was successfully updated. Please log in to continue.')->flash();
}
return redirect($this->hasTwoFactor ? route('auth.login') : $this->redirectPath())
->with('status', trans($response));
}
}

View file

@ -3,7 +3,9 @@
namespace Pterodactyl\Http\Controllers\Base;
use Pterodactyl\Models\User;
use Illuminate\Auth\AuthManager;
use Prologue\Alerts\AlertsMessageBag;
use Illuminate\Contracts\Session\Session;
use Pterodactyl\Http\Controllers\Controller;
use Pterodactyl\Services\Users\UserUpdateService;
use Pterodactyl\Traits\Helpers\AvailableLanguages;
@ -18,6 +20,11 @@ class AccountController extends Controller
*/
protected $alert;
/**
* @var \Illuminate\Auth\SessionGuard
*/
protected $sessionGuard;
/**
* @var \Pterodactyl\Services\Users\UserUpdateService
*/
@ -27,12 +34,14 @@ class AccountController extends Controller
* AccountController constructor.
*
* @param \Prologue\Alerts\AlertsMessageBag $alert
* @param \Illuminate\Auth\AuthManager $authManager
* @param \Pterodactyl\Services\Users\UserUpdateService $updateService
*/
public function __construct(AlertsMessageBag $alert, UserUpdateService $updateService)
public function __construct(AlertsMessageBag $alert, AuthManager $authManager, UserUpdateService $updateService)
{
$this->alert = $alert;
$this->updateService = $updateService;
$this->sessionGuard = $authManager->guard();
}
/**
@ -55,21 +64,26 @@ class AccountController extends Controller
*
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
* @throws \Pterodactyl\Exceptions\Http\Connection\DaemonConnectionException
*/
public function update(AccountDataFormRequest $request)
{
$data = [];
// Prevent logging this specific session out when the password is changed. This will
// automatically update the user's password anyways, so no need to do anything else here.
if ($request->input('do_action') === 'password') {
$data['password'] = $request->input('new_password');
} elseif ($request->input('do_action') === 'email') {
$data['email'] = $request->input('new_email');
} elseif ($request->input('do_action') === 'identity') {
$data = $request->only(['name_first', 'name_last', 'username', 'language']);
$this->sessionGuard->logoutOtherDevices($request->input('new_password'));
} else {
if ($request->input('do_action') === 'email') {
$data = ['email' => $request->input('new_email')];
} elseif ($request->input('do_action') === 'identity') {
$data = $request->only(['name_first', 'name_last', 'username', 'language']);
} else {
$data = [];
}
$this->updateService->setUserLevel(User::USER_LEVEL_USER);
$this->updateService->handle($request->user(), $data);
}
$this->updateService->setUserLevel(User::USER_LEVEL_USER);
$this->updateService->handle($request->user(), $data);
$this->alert->success(trans('base.account.details_updated'))->flash();
return redirect()->route('account');

View file

@ -7,9 +7,26 @@ use Illuminate\Http\Request;
use Pterodactyl\Models\Node;
use Pterodactyl\Models\Server;
use Pterodactyl\Http\Controllers\Controller;
use Pterodactyl\Events\Server\Installed as ServerInstalled;
use Illuminate\Contracts\Events\Dispatcher as EventDispatcher;
class ActionController extends Controller
{
/**
* @var \Illuminate\Contracts\Events\Dispatcher
*/
private $eventDispatcher;
/**
* ActionController constructor.
*
* @param \Illuminate\Contracts\Events\Dispatcher $eventDispatcher
*/
public function __construct(EventDispatcher $eventDispatcher)
{
$this->eventDispatcher = $eventDispatcher;
}
/**
* Handles install toggle request from daemon.
*
@ -37,6 +54,11 @@ class ActionController extends Controller
$server->installed = ($status === 'installed') ? 1 : 2;
$server->save();
// Only fire event if server installed successfully.
if ($server->installed === 1) {
$this->eventDispatcher->dispatch(new ServerInstalled($server));
}
return response()->json([]);
}

View file

@ -157,7 +157,6 @@ class SubuserController extends Controller
* @return \Illuminate\Http\RedirectResponse
*
* @throws \Exception
* @throws \Illuminate\Auth\Access\AuthorizationException
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
* @throws \Pterodactyl\Exceptions\Service\Subuser\ServerSubuserExistsException
@ -171,7 +170,7 @@ class SubuserController extends Controller
$this->alert->success(trans('server.users.user_assigned'))->flash();
return redirect()->route('server.subusers.view', [
'uuid' => $server->uuid,
'uuid' => $server->uuidShort,
'id' => $subuser->hashid,
]);
}

View file

@ -2,7 +2,6 @@
namespace Pterodactyl\Http\Controllers\Server\Tasks;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Pterodactyl\Http\Controllers\Controller;
@ -11,12 +10,22 @@ use Pterodactyl\Contracts\Repository\ScheduleRepositoryInterface;
class ActionController extends Controller
{
/**
* @var \Pterodactyl\Services\Schedules\ProcessScheduleService
*/
private $processScheduleService;
/**
* @var \Pterodactyl\Contracts\Repository\ScheduleRepositoryInterface
*/
private $repository;
/**
* ActionController constructor.
*
* @param \Pterodactyl\Services\Schedules\ProcessScheduleService $processScheduleService
* @param \Pterodactyl\Contracts\Repository\ScheduleRepositoryInterface $repository
*/
public function __construct(ProcessScheduleService $processScheduleService, ScheduleRepositoryInterface $repository)
{
$this->processScheduleService = $processScheduleService;
@ -61,7 +70,7 @@ class ActionController extends Controller
$server = $request->attributes->get('server');
$this->authorize('toggle-schedule', $server);
$this->processScheduleService->setRunTimeOverride(Carbon::now())->handle(
$this->processScheduleService->handle(
$request->attributes->get('schedule')
);

View file

@ -2,7 +2,6 @@
namespace Pterodactyl\Http;
use Pterodactyl\Http\Middleware\MaintenanceMiddleware;
use Pterodactyl\Models\ApiKey;
use Illuminate\Auth\Middleware\Authorize;
use Illuminate\Auth\Middleware\Authenticate;
@ -18,15 +17,17 @@ use Pterodactyl\Http\Middleware\LanguageMiddleware;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
use Pterodactyl\Http\Middleware\Api\AuthenticateKey;
use Illuminate\Routing\Middleware\SubstituteBindings;
use Pterodactyl\Http\Middleware\AccessingValidServer;
use Pterodactyl\Http\Middleware\Api\SetSessionDriver;
use Illuminate\Session\Middleware\AuthenticateSession;
use Illuminate\View\Middleware\ShareErrorsFromSession;
use Pterodactyl\Http\Middleware\MaintenanceMiddleware;
use Pterodactyl\Http\Middleware\RedirectIfAuthenticated;
use Illuminate\Auth\Middleware\AuthenticateWithBasicAuth;
use Pterodactyl\Http\Middleware\Api\AuthenticateIPAccess;
use Pterodactyl\Http\Middleware\Api\ApiSubstituteBindings;
use Illuminate\Foundation\Http\Middleware\ValidatePostSize;
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Pterodactyl\Http\Middleware\Server\AccessingValidServer;
use Pterodactyl\Http\Middleware\Server\AuthenticateAsSubuser;
use Pterodactyl\Http\Middleware\Api\Daemon\DaemonAuthenticate;
use Pterodactyl\Http\Middleware\Server\SubuserBelongsToServer;
@ -64,6 +65,7 @@ class Kernel extends HttpKernel
EncryptCookies::class,
AddQueuedCookiesToResponse::class,
StartSession::class,
AuthenticateSession::class,
ShareErrorsFromSession::class,
VerifyCsrfToken::class,
SubstituteBindings::class,

View file

@ -1,6 +1,6 @@
<?php
namespace Pterodactyl\Http\Middleware;
namespace Pterodactyl\Http\Middleware\Server;
use Closure;
use Illuminate\Http\Request;

View file

@ -74,7 +74,7 @@ class StoreNodeRequest extends ApplicationApiRequest
$response = parent::validated();
$response['daemonListen'] = $response['daemon_listen'];
$response['daemonSFTP'] = $response['daemon_sftp'];
$response['daemonBase'] = $response['daemon_base'];
$response['daemonBase'] = $response['daemon_base'] ?? (new Node)->getAttribute('daemonBase');
unset($response['daemon_base'], $response['daemon_listen'], $response['daemon_sftp']);

View file

@ -25,7 +25,7 @@ class SubuserStoreFormRequest extends ServerFormRequest
{
return [
'email' => 'required|email',
'permissions' => 'present|array',
'permissions' => 'sometimes|array',
];
}
}

View file

@ -3,7 +3,7 @@
namespace Pterodactyl\Jobs\Schedule;
use Exception;
use Carbon\Carbon;
use Cake\Chronos\Chronos;
use Pterodactyl\Jobs\Job;
use InvalidArgumentException;
use Illuminate\Queue\SerializesModels;
@ -158,7 +158,7 @@ class RunTaskJob extends Job implements ShouldQueue
$repository = app()->make(ScheduleRepositoryInterface::class);
$repository->withoutFreshModel()->update($this->schedule, [
'is_processing' => false,
'last_run_at' => Carbon::now()->toDateTimeString(),
'last_run_at' => Chronos::now()->toDateTimeString(),
]);
}

View file

View file

@ -113,6 +113,7 @@ class Node extends Model implements CleansAttributes, ValidableContract
'daemonSFTP' => 'numeric|between:1024,65535',
'daemonListen' => 'numeric|between:1024,65535',
'maintenance_mode' => 'boolean',
'upload_size' => 'int|between:1,1024',
];
/**

View file

@ -23,7 +23,7 @@ class AccountCreated extends Notification implements ShouldQueue
/**
* The user model for the created user.
*
* @var object
* @var \Pterodactyl\Models\User
*/
public $user;
@ -65,7 +65,7 @@ class AccountCreated extends Notification implements ShouldQueue
->line('Email: ' . $this->user->email);
if (! is_null($this->token)) {
return $message->action('Setup Your Account', url('/auth/password/reset/' . $this->token . '?email=' . $this->user->email));
return $message->action('Setup Your Account', url('/auth/password/reset/' . $this->token . '?email=' . urlencode($this->user->email)));
}
return $message;

View file

@ -0,0 +1,69 @@
<?php
namespace Pterodactyl\Notifications;
use Illuminate\Bus\Queueable;
use Pterodactyl\Events\Event;
use Illuminate\Container\Container;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Pterodactyl\Contracts\Core\ReceivesEvents;
use Illuminate\Contracts\Notifications\Dispatcher;
use Illuminate\Notifications\Messages\MailMessage;
class ServerInstalled extends Notification implements ShouldQueue, ReceivesEvents
{
use Queueable;
/**
* @var \Pterodactyl\Models\Server
*/
public $server;
/**
* @var \Pterodactyl\Models\User
*/
public $user;
/**
* Handle a direct call to this notification from the server installed event. This is configured
* in the event service provider.
*
* @param \Pterodactyl\Events\Event|\Pterodactyl\Events\Server\Installed $event
*/
public function handle(Event $event): void
{
$event->server->loadMissing('user');
$this->server = $event->server;
$this->user = $event->server->user;
// Since we are calling this notification directly from an event listener we need to fire off the dispatcher
// to send the email now. Don't use send() or you'll end up firing off two different events.
Container::getInstance()->make(Dispatcher::class)->sendNow($this->user, $this);
}
/**
* Get the notification's delivery channels.
*
* @return array
*/
public function via()
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail()
{
return (new MailMessage)
->greeting('Hello ' . $this->user->username . '.')
->line('Your server has finished installing and is now ready for you to use.')
->line('Server Name: ' . $this->server->name)
->action('Login and Begin Using', route('index'));
}
}

View file

@ -2,6 +2,8 @@
namespace Pterodactyl\Providers;
use Pterodactyl\Events\Server\Installed as ServerInstalledEvent;
use Pterodactyl\Notifications\ServerInstalled as ServerInstalledNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
@ -11,5 +13,9 @@ class EventServiceProvider extends ServiceProvider
*
* @var array
*/
protected $listen = [];
protected $listen = [
ServerInstalledEvent::class => [
ServerInstalledNotification::class,
],
];
}

View file

@ -144,6 +144,7 @@ abstract class BaseRepository implements BaseRepositoryInterface
$headers['X-Access-Token'] = $this->getToken() ?? $this->getNode()->daemonSecret;
return new Client([
'verify' => config('app.env') === 'production',
'base_uri' => sprintf('%s://%s:%s/v1/', $this->getNode()->scheme, $this->getNode()->fqdn, $this->getNode()->daemonListen),
'timeout' => config('pterodactyl.guzzle.timeout'),
'connect_timeout' => config('pterodactyl.guzzle.connect_timeout'),

View file

@ -298,7 +298,7 @@ abstract class EloquentRepository extends Repository implements RepositoryInterf
}
/**
* Get the amount of entries in the database
* Get the amount of entries in the database.
*
* @return int
*/

View file

@ -75,6 +75,7 @@ class ScheduleRepository extends EloquentRepository implements ScheduleRepositor
{
return $this->getBuilder()->with('tasks')
->where('is_active', true)
->where('is_processing', false)
->where('next_run_at', '<=', $timestamp)
->get($this->getColumns());
}

View file

@ -330,7 +330,7 @@ class ServerRepository extends EloquentRepository implements ServerRepositoryInt
}
/**
* Get the amount of servers that are suspended
* Get the amount of servers that are suspended.
*
* @return int
*/

View file

@ -1,59 +0,0 @@
<?php
/**
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* This software is licensed under the terms of the MIT license.
* https://opensource.org/licenses/MIT
*/
namespace Pterodactyl\Services\Helpers;
use Ramsey\Uuid\Uuid;
use Illuminate\Contracts\Hashing\Hasher;
use Illuminate\Database\ConnectionInterface;
class TemporaryPasswordService
{
const HMAC_ALGO = 'sha256';
/**
* @var \Illuminate\Database\ConnectionInterface
*/
protected $connection;
/**
* @var \Illuminate\Contracts\Hashing\Hasher
*/
protected $hasher;
/**
* TemporaryPasswordService constructor.
*
* @param \Illuminate\Database\ConnectionInterface $connection
* @param \Illuminate\Contracts\Hashing\Hasher $hasher
*/
public function __construct(ConnectionInterface $connection, Hasher $hasher)
{
$this->connection = $connection;
$this->hasher = $hasher;
}
/**
* Store a password reset token for a specific email address.
*
* @param string $email
* @return string
*/
public function handle($email)
{
$token = hash_hmac(self::HMAC_ALGO, Uuid::uuid4()->toString(), config('app.key'));
$this->connection->table('password_resets')->insert([
'email' => $email,
'token' => $this->hasher->make($token),
]);
return $token;
}
}

View file

@ -1,11 +1,4 @@
<?php
/**
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* This software is licensed under the terms of the MIT license.
* https://opensource.org/licenses/MIT
*/
namespace Pterodactyl\Services\Nodes;
@ -13,7 +6,6 @@ use Pterodactyl\Models\Node;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Database\ConnectionInterface;
use Pterodactyl\Traits\Services\ReturnsUpdatedModels;
use Pterodactyl\Contracts\Repository\NodeRepositoryInterface;
use Pterodactyl\Exceptions\Http\Connection\DaemonConnectionException;
use Pterodactyl\Exceptions\Service\Node\ConfigurationNotPersistedException;
@ -21,8 +13,6 @@ use Pterodactyl\Contracts\Repository\Daemon\ConfigurationRepositoryInterface;
class NodeUpdateService
{
use ReturnsUpdatedModels;
/**
* @var \Illuminate\Database\ConnectionInterface
*/
@ -60,7 +50,7 @@ class NodeUpdateService
*
* @param \Pterodactyl\Models\Node $node
* @param array $data
* @return \Pterodactyl\Models\Node|mixed
* @return \Pterodactyl\Models\Node
*
* @throws \Pterodactyl\Exceptions\DisplayException
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
@ -74,14 +64,10 @@ class NodeUpdateService
}
$this->connection->beginTransaction();
if ($this->getUpdatedModel()) {
$response = $this->repository->update($node->id, $data);
} else {
$response = $this->repository->withoutFreshModel()->update($node->id, $data);
}
$updatedModel = $this->repository->update($node->id, $data);
try {
$this->configRepository->setNode($node)->update();
$this->configRepository->setNode($updatedModel)->update();
$this->connection->commit();
} catch (RequestException $exception) {
// Failed to connect to the Daemon. Let's go ahead and save the configuration
@ -95,6 +81,6 @@ class NodeUpdateService
throw new DaemonConnectionException($exception);
}
return $response;
return $updatedModel;
}
}

View file

@ -2,53 +2,45 @@
namespace Pterodactyl\Services\Schedules;
use Carbon\Carbon;
use Cron\CronExpression;
use Pterodactyl\Models\Schedule;
use Pterodactyl\Services\Schedules\Tasks\RunTaskService;
use Illuminate\Contracts\Bus\Dispatcher;
use Pterodactyl\Jobs\Schedule\RunTaskJob;
use Pterodactyl\Contracts\Repository\TaskRepositoryInterface;
use Pterodactyl\Contracts\Repository\ScheduleRepositoryInterface;
class ProcessScheduleService
{
/**
* @var \Illuminate\Contracts\Bus\Dispatcher
*/
private $dispatcher;
/**
* @var \Pterodactyl\Contracts\Repository\ScheduleRepositoryInterface
*/
private $repository;
private $scheduleRepository;
/**
* @var \Pterodactyl\Services\Schedules\Tasks\RunTaskService
* @var \Pterodactyl\Contracts\Repository\TaskRepositoryInterface
*/
private $runnerService;
/**
* @var \Carbon\Carbon|null
*/
private $runTimeOverride;
private $taskRepository;
/**
* ProcessScheduleService constructor.
*
* @param \Pterodactyl\Services\Schedules\Tasks\RunTaskService $runnerService
* @param \Pterodactyl\Contracts\Repository\ScheduleRepositoryInterface $repository
* @param \Illuminate\Contracts\Bus\Dispatcher $dispatcher
* @param \Pterodactyl\Contracts\Repository\ScheduleRepositoryInterface $scheduleRepository
* @param \Pterodactyl\Contracts\Repository\TaskRepositoryInterface $taskRepository
*/
public function __construct(RunTaskService $runnerService, ScheduleRepositoryInterface $repository)
{
$this->repository = $repository;
$this->runnerService = $runnerService;
}
/**
* Set the time that this schedule should be run at. This will override the time
* defined on the schedule itself. Useful for triggering one-off task runs.
*
* @param \Carbon\Carbon $time
* @return $this
*/
public function setRunTimeOverride(Carbon $time)
{
$this->runTimeOverride = $time;
return $this;
public function __construct(
Dispatcher $dispatcher,
ScheduleRepositoryInterface $scheduleRepository,
TaskRepositoryInterface $taskRepository
) {
$this->dispatcher = $dispatcher;
$this->scheduleRepository = $scheduleRepository;
$this->taskRepository = $taskRepository;
}
/**
@ -61,7 +53,10 @@ class ProcessScheduleService
*/
public function handle(Schedule $schedule)
{
$this->repository->loadTasks($schedule);
$this->scheduleRepository->loadTasks($schedule);
/** @var \Pterodactyl\Models\Task $task */
$task = $schedule->getRelation('tasks')->where('sequence_id', 1)->first();
$formattedCron = sprintf('%s %s %s * %s',
$schedule->cron_minute,
@ -70,27 +65,15 @@ class ProcessScheduleService
$schedule->cron_day_of_week
);
$this->repository->update($schedule->id, [
$this->scheduleRepository->update($schedule->id, [
'is_processing' => true,
'next_run_at' => $this->getRunAtTime($formattedCron),
'next_run_at' => CronExpression::factory($formattedCron)->getNextRunDate(),
]);
$task = $schedule->getRelation('tasks')->where('sequence_id', 1)->first();
$this->runnerService->handle($task);
}
$this->taskRepository->update($task->id, ['is_queued' => true]);
/**
* Get the timestamp to store in the database as the next_run time for a schedule.
*
* @param string $formatted
* @return \DateTime|string
*/
private function getRunAtTime(string $formatted)
{
if ($this->runTimeOverride instanceof Carbon) {
return $this->runTimeOverride->toDateTimeString();
}
return CronExpression::factory($formatted)->getNextRunDate();
$this->dispatcher->dispatch(
(new RunTaskJob($task->id, $schedule->id))->delay($task->time_offset)
);
}
}

View file

@ -1,53 +0,0 @@
<?php
/**
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* This software is licensed under the terms of the MIT license.
* https://opensource.org/licenses/MIT
*/
namespace Pterodactyl\Services\Schedules\Tasks;
use Pterodactyl\Models\Task;
use Pterodactyl\Jobs\Schedule\RunTaskJob;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Pterodactyl\Contracts\Repository\TaskRepositoryInterface;
class RunTaskService
{
use DispatchesJobs;
/**
* @var \Pterodactyl\Contracts\Repository\TaskRepositoryInterface
*/
protected $repository;
/**
* RunTaskService constructor.
*
* @param \Pterodactyl\Contracts\Repository\TaskRepositoryInterface $repository
*/
public function __construct(TaskRepositoryInterface $repository)
{
$this->repository = $repository;
}
/**
* Push a single task onto the queue.
*
* @param int|\Pterodactyl\Models\Task $task
*
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
*/
public function handle($task)
{
if (! $task instanceof Task) {
$task = $this->repository->find($task);
}
$this->repository->update($task->id, ['is_queued' => true]);
$this->dispatch((new RunTaskJob($task->id, $task->schedule_id))->delay($task->time_offset));
}
}

View file

@ -78,7 +78,7 @@ class EnvironmentService
}
// Process variables set in the configuration file.
foreach ($this->config->get('pterodactyl.environment_mappings', []) as $key => $object) {
foreach ($this->config->get('pterodactyl.environment_variables', []) as $key => $object) {
if (is_callable($object)) {
$variables[$key] = call_user_func($object, $server);
} else {

View file

@ -56,6 +56,8 @@ class PermissionCreationService
}
}
$this->repository->withoutFreshModel()->insert($insertPermissions);
if (! empty($insertPermissions)) {
$this->repository->withoutFreshModel()->insert($insertPermissions);
}
}
}

View file

@ -5,8 +5,8 @@ namespace Pterodactyl\Services\Users;
use Ramsey\Uuid\Uuid;
use Illuminate\Contracts\Hashing\Hasher;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Contracts\Auth\PasswordBroker;
use Pterodactyl\Notifications\AccountCreated;
use Pterodactyl\Services\Helpers\TemporaryPasswordService;
use Pterodactyl\Contracts\Repository\UserRepositoryInterface;
class UserCreationService
@ -22,9 +22,9 @@ class UserCreationService
private $hasher;
/**
* @var \Pterodactyl\Services\Helpers\TemporaryPasswordService
* @var \Illuminate\Contracts\Auth\PasswordBroker
*/
private $passwordService;
private $passwordBroker;
/**
* @var \Pterodactyl\Contracts\Repository\UserRepositoryInterface
@ -36,18 +36,18 @@ class UserCreationService
*
* @param \Illuminate\Database\ConnectionInterface $connection
* @param \Illuminate\Contracts\Hashing\Hasher $hasher
* @param \Pterodactyl\Services\Helpers\TemporaryPasswordService $passwordService
* @param \Illuminate\Contracts\Auth\PasswordBroker $passwordBroker
* @param \Pterodactyl\Contracts\Repository\UserRepositoryInterface $repository
*/
public function __construct(
ConnectionInterface $connection,
Hasher $hasher,
TemporaryPasswordService $passwordService,
PasswordBroker $passwordBroker,
UserRepositoryInterface $repository
) {
$this->connection = $connection;
$this->hasher = $hasher;
$this->passwordService = $passwordService;
$this->passwordBroker = $passwordBroker;
$this->repository = $repository;
}
@ -68,8 +68,8 @@ class UserCreationService
$this->connection->beginTransaction();
if (! isset($data['password']) || empty($data['password'])) {
$generateResetToken = true;
$data['password'] = $this->hasher->make(str_random(30));
$token = $this->passwordService->handle($data['email']);
}
/** @var \Pterodactyl\Models\User $user */
@ -77,6 +77,10 @@ class UserCreationService
'uuid' => Uuid::uuid4()->toString(),
]), true, true);
if (isset($generateResetToken)) {
$token = $this->passwordBroker->createToken($user);
}
$this->connection->commit();
$user->notify(new AccountCreated($user, $token ?? null));

View file

@ -3,7 +3,7 @@
* Created by PhpStorm.
* User: Stan
* Date: 26-5-2018
* Time: 20:56
* Time: 20:56.
*/
namespace Pterodactyl\Traits\Controllers;
@ -12,13 +12,11 @@ use JavaScript;
trait PlainJavascriptInjection
{
/**
* Injects statistics into javascript
* Injects statistics into javascript.
*/
public function injectJavascript($data)
{
Javascript::put($data);
}
}
}