Replace database repository

This commit is contained in:
Lance Pioch 2022-10-24 00:19:14 -04:00
parent e49ba65709
commit 483c081d7f
9 changed files with 102 additions and 248 deletions

View file

@ -1,61 +0,0 @@
<?php
namespace Pterodactyl\Contracts\Repository;
use Illuminate\Support\Collection;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
interface DatabaseRepositoryInterface extends RepositoryInterface
{
public const DEFAULT_CONNECTION_NAME = 'dynamic';
/**
* Set the connection name to execute statements against.
*/
public function setConnection(string $connection): self;
/**
* Return the connection to execute statements against.
*/
public function getConnection(): string;
/**
* Return all the databases belonging to a server.
*/
public function getDatabasesForServer(int $server): Collection;
/**
* Return all the databases for a given host with the server relationship loaded.
*/
public function getDatabasesForHost(int $host, int $count = 25): LengthAwarePaginator;
/**
* Create a new database on a given connection.
*/
public function createDatabase(string $database): bool;
/**
* Create a new database user on a given connection.
*/
public function createUser(string $username, string $remote, string $password, ?int $max_connections): bool;
/**
* Give a specific user access to a given database.
*/
public function assignUserToDatabase(string $database, string $username, string $remote): bool;
/**
* Flush the privileges for a given connection.
*/
public function flush(): bool;
/**
* Drop a given database on a specific connection.
*/
public function dropDatabase(string $database): bool;
/**
* Drop a given user on a specific connection.
*/
public function dropUser(string $username, string $remote): bool;
}

View file

@ -14,7 +14,6 @@ use Pterodactyl\Services\Databases\Hosts\HostUpdateService;
use Pterodactyl\Http\Requests\Admin\DatabaseHostFormRequest; use Pterodactyl\Http\Requests\Admin\DatabaseHostFormRequest;
use Pterodactyl\Services\Databases\Hosts\HostCreationService; use Pterodactyl\Services\Databases\Hosts\HostCreationService;
use Pterodactyl\Services\Databases\Hosts\HostDeletionService; use Pterodactyl\Services\Databases\Hosts\HostDeletionService;
use Pterodactyl\Contracts\Repository\DatabaseRepositoryInterface;
use Pterodactyl\Contracts\Repository\LocationRepositoryInterface; use Pterodactyl\Contracts\Repository\LocationRepositoryInterface;
use Pterodactyl\Contracts\Repository\DatabaseHostRepositoryInterface; use Pterodactyl\Contracts\Repository\DatabaseHostRepositoryInterface;
@ -26,7 +25,6 @@ class DatabaseController extends Controller
public function __construct( public function __construct(
private AlertsMessageBag $alert, private AlertsMessageBag $alert,
private DatabaseHostRepositoryInterface $repository, private DatabaseHostRepositoryInterface $repository,
private DatabaseRepositoryInterface $databaseRepository,
private HostCreationService $creationService, private HostCreationService $creationService,
private HostDeletionService $deletionService, private HostDeletionService $deletionService,
private HostUpdateService $updateService, private HostUpdateService $updateService,
@ -49,14 +47,17 @@ class DatabaseController extends Controller
/** /**
* Display database host to user. * Display database host to user.
* *
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
*/ */
public function view(int $host): View public function view(int $host): View
{ {
/** @var DatabaseHost $host */
$host = DatabaseHost::query()->findOrFail($host);
$databases = $host->databases()->with('server')->paginate(25);
return $this->view->make('admin.databases.view', [ return $this->view->make('admin.databases.view', [
'locations' => $this->locationRepository->getAllWithNodes(), 'locations' => $this->locationRepository->getAllWithNodes(),
'host' => $this->repository->find($host), 'host' => $host,
'databases' => $this->databaseRepository->getDatabasesForHost($host), 'databases' => $databases,
]); ]);
} }

View file

@ -29,7 +29,6 @@ use Pterodactyl\Repositories\Eloquent\DatabaseHostRepository;
use Pterodactyl\Services\Databases\DatabaseManagementService; use Pterodactyl\Services\Databases\DatabaseManagementService;
use Illuminate\Contracts\Config\Repository as ConfigRepository; use Illuminate\Contracts\Config\Repository as ConfigRepository;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface; use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
use Pterodactyl\Contracts\Repository\DatabaseRepositoryInterface;
use Pterodactyl\Contracts\Repository\AllocationRepositoryInterface; use Pterodactyl\Contracts\Repository\AllocationRepositoryInterface;
use Pterodactyl\Services\Servers\ServerConfigurationStructureService; use Pterodactyl\Services\Servers\ServerConfigurationStructureService;
use Pterodactyl\Http\Requests\Admin\Servers\Databases\StoreServerDatabaseRequest; use Pterodactyl\Http\Requests\Admin\Servers\Databases\StoreServerDatabaseRequest;
@ -47,7 +46,6 @@ class ServersController extends Controller
protected DaemonServerRepository $daemonServerRepository, protected DaemonServerRepository $daemonServerRepository,
protected DatabaseManagementService $databaseManagementService, protected DatabaseManagementService $databaseManagementService,
protected DatabasePasswordService $databasePasswordService, protected DatabasePasswordService $databasePasswordService,
protected DatabaseRepositoryInterface $databaseRepository,
protected DatabaseHostRepository $databaseHostRepository, protected DatabaseHostRepository $databaseHostRepository,
protected ServerDeletionService $deletionService, protected ServerDeletionService $deletionService,
protected DetailsModificationService $detailsModificationService, protected DetailsModificationService $detailsModificationService,

View file

@ -4,6 +4,7 @@ namespace Pterodactyl\Models;
use Illuminate\Container\Container; use Illuminate\Container\Container;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\DB;
use Pterodactyl\Contracts\Extensions\HashidsInterface; use Pterodactyl\Contracts\Extensions\HashidsInterface;
/** /**
@ -28,10 +29,7 @@ class Database extends Model
*/ */
public const RESOURCE_NAME = 'server_database'; public const RESOURCE_NAME = 'server_database';
/** public const DEFAULT_CONNECTION_NAME = 'dynamic';
* The table associated with the model.
*/
protected $table = 'databases';
/** /**
* The attributes excluded from the model's JSON form. * The attributes excluded from the model's JSON form.
@ -107,4 +105,73 @@ class Database extends Model
{ {
return $this->belongsTo(Server::class); return $this->belongsTo(Server::class);
} }
/**
* Run the provided statement against the database on a given connection.
*/
private function run(string $statement): bool
{
return DB::connection($this->connection)->statement($statement);
}
/**
* Create a new database on a given connection.
*/
public function createDatabase(string $database): bool
{
return $this->run(sprintf('CREATE DATABASE IF NOT EXISTS `%s`', $database));
}
/**
* Create a new database user on a given connection.
*/
public function createUser(string $username, string $remote, string $password, ?int $max_connections): bool
{
$args = [$username, $remote, $password];
$command = 'CREATE USER `%s`@`%s` IDENTIFIED BY \'%s\'';
if (!empty($max_connections)) {
$args[] = $max_connections;
$command .= ' WITH MAX_USER_CONNECTIONS %s';
}
return $this->run(sprintf($command, ...$args));
}
/**
* Give a specific user access to a given database.
*/
public function assignUserToDatabase(string $database, string $username, string $remote): bool
{
return $this->run(sprintf(
'GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER, REFERENCES, INDEX, LOCK TABLES, CREATE ROUTINE, ALTER ROUTINE, EXECUTE, CREATE TEMPORARY TABLES, CREATE VIEW, SHOW VIEW, EVENT, TRIGGER ON `%s`.* TO `%s`@`%s`',
$database,
$username,
$remote
));
}
/**
* Flush the privileges for a given connection.
*/
public function flush(): bool
{
return $this->run('FLUSH PRIVILEGES');
}
/**
* Drop a given database on a specific connection.
*/
public function dropDatabase(string $database): bool
{
return $this->run(sprintf('DROP DATABASE IF EXISTS `%s`', $database));
}
/**
* Drop a given user on a specific connection.
*/
public function dropUser(string $username, string $remote): bool
{
return $this->run(sprintf('DROP USER IF EXISTS `%s`@`%s`', $username, $remote));
}
} }

View file

@ -12,7 +12,6 @@ use Pterodactyl\Repositories\Eloquent\ApiKeyRepository;
use Pterodactyl\Repositories\Eloquent\ServerRepository; use Pterodactyl\Repositories\Eloquent\ServerRepository;
use Pterodactyl\Repositories\Eloquent\SessionRepository; use Pterodactyl\Repositories\Eloquent\SessionRepository;
use Pterodactyl\Repositories\Eloquent\SubuserRepository; use Pterodactyl\Repositories\Eloquent\SubuserRepository;
use Pterodactyl\Repositories\Eloquent\DatabaseRepository;
use Pterodactyl\Repositories\Eloquent\LocationRepository; use Pterodactyl\Repositories\Eloquent\LocationRepository;
use Pterodactyl\Repositories\Eloquent\ScheduleRepository; use Pterodactyl\Repositories\Eloquent\ScheduleRepository;
use Pterodactyl\Repositories\Eloquent\SettingsRepository; use Pterodactyl\Repositories\Eloquent\SettingsRepository;
@ -29,7 +28,6 @@ use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
use Pterodactyl\Repositories\Eloquent\ServerVariableRepository; use Pterodactyl\Repositories\Eloquent\ServerVariableRepository;
use Pterodactyl\Contracts\Repository\SessionRepositoryInterface; use Pterodactyl\Contracts\Repository\SessionRepositoryInterface;
use Pterodactyl\Contracts\Repository\SubuserRepositoryInterface; use Pterodactyl\Contracts\Repository\SubuserRepositoryInterface;
use Pterodactyl\Contracts\Repository\DatabaseRepositoryInterface;
use Pterodactyl\Contracts\Repository\LocationRepositoryInterface; use Pterodactyl\Contracts\Repository\LocationRepositoryInterface;
use Pterodactyl\Contracts\Repository\ScheduleRepositoryInterface; use Pterodactyl\Contracts\Repository\ScheduleRepositoryInterface;
use Pterodactyl\Contracts\Repository\SettingsRepositoryInterface; use Pterodactyl\Contracts\Repository\SettingsRepositoryInterface;
@ -48,7 +46,6 @@ class RepositoryServiceProvider extends ServiceProvider
// Eloquent Repositories // Eloquent Repositories
$this->app->bind(AllocationRepositoryInterface::class, AllocationRepository::class); $this->app->bind(AllocationRepositoryInterface::class, AllocationRepository::class);
$this->app->bind(ApiKeyRepositoryInterface::class, ApiKeyRepository::class); $this->app->bind(ApiKeyRepositoryInterface::class, ApiKeyRepository::class);
$this->app->bind(DatabaseRepositoryInterface::class, DatabaseRepository::class);
$this->app->bind(DatabaseHostRepositoryInterface::class, DatabaseHostRepository::class); $this->app->bind(DatabaseHostRepositoryInterface::class, DatabaseHostRepository::class);
$this->app->bind(EggRepositoryInterface::class, EggRepository::class); $this->app->bind(EggRepositoryInterface::class, EggRepository::class);
$this->app->bind(EggVariableRepositoryInterface::class, EggVariableRepository::class); $this->app->bind(EggVariableRepositoryInterface::class, EggVariableRepository::class);

View file

@ -1,136 +0,0 @@
<?php
namespace Pterodactyl\Repositories\Eloquent;
use Pterodactyl\Models\Database;
use Illuminate\Support\Collection;
use Illuminate\Foundation\Application;
use Illuminate\Database\DatabaseManager;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Pterodactyl\Contracts\Repository\DatabaseRepositoryInterface;
class DatabaseRepository extends EloquentRepository implements DatabaseRepositoryInterface
{
protected string $connection = self::DEFAULT_CONNECTION_NAME;
/**
* DatabaseRepository constructor.
*/
public function __construct(Application $application, private DatabaseManager $database)
{
parent::__construct($application);
}
/**
* Return the model backing this repository.
*/
public function model(): string
{
return Database::class;
}
/**
* Return the connection to execute statements against.
*/
public function getConnection(): string
{
return $this->connection;
}
/**
* Set the connection name to execute statements against.
*/
public function setConnection(string $connection): self
{
$this->connection = $connection;
return $this;
}
/**
* Return all the databases belonging to a server.
*/
public function getDatabasesForServer(int $server): Collection
{
return $this->getBuilder()->with('host')->where('server_id', $server)->get($this->getColumns());
}
/**
* Return all the databases for a given host with the server relationship loaded.
*/
public function getDatabasesForHost(int $host, int $count = 25): LengthAwarePaginator
{
return $this->getBuilder()->with('server')
->where('database_host_id', $host)
->paginate($count, $this->getColumns());
}
/**
* Create a new database on a given connection.
*/
public function createDatabase(string $database): bool
{
return $this->run(sprintf('CREATE DATABASE IF NOT EXISTS `%s`', $database));
}
/**
* Create a new database user on a given connection.
*/
public function createUser(string $username, string $remote, string $password, ?int $max_connections): bool
{
$args = [$username, $remote, $password];
$command = 'CREATE USER `%s`@`%s` IDENTIFIED BY \'%s\'';
if (!empty($max_connections)) {
$args[] = $max_connections;
$command .= ' WITH MAX_USER_CONNECTIONS %s';
}
return $this->run(sprintf($command, ...$args));
}
/**
* Give a specific user access to a given database.
*/
public function assignUserToDatabase(string $database, string $username, string $remote): bool
{
return $this->run(sprintf(
'GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER, REFERENCES, INDEX, LOCK TABLES, CREATE ROUTINE, ALTER ROUTINE, EXECUTE, CREATE TEMPORARY TABLES, CREATE VIEW, SHOW VIEW, EVENT, TRIGGER ON `%s`.* TO `%s`@`%s`',
$database,
$username,
$remote
));
}
/**
* Flush the privileges for a given connection.
*/
public function flush(): bool
{
return $this->run('FLUSH PRIVILEGES');
}
/**
* Drop a given database on a specific connection.
*/
public function dropDatabase(string $database): bool
{
return $this->run(sprintf('DROP DATABASE IF EXISTS `%s`', $database));
}
/**
* Drop a given user on a specific connection.
*/
public function dropUser(string $username, string $remote): bool
{
return $this->run(sprintf('DROP USER IF EXISTS `%s`@`%s`', $username, $remote));
}
/**
* Run the provided statement against the database on a given connection.
*/
private function run(string $statement): bool
{
return $this->database->connection($this->getConnection())->statement($statement);
}
}

View file

@ -10,7 +10,6 @@ use Pterodactyl\Helpers\Utilities;
use Illuminate\Database\ConnectionInterface; use Illuminate\Database\ConnectionInterface;
use Illuminate\Contracts\Encryption\Encrypter; use Illuminate\Contracts\Encryption\Encrypter;
use Pterodactyl\Extensions\DynamicDatabaseConnection; use Pterodactyl\Extensions\DynamicDatabaseConnection;
use Pterodactyl\Repositories\Eloquent\DatabaseRepository;
use Pterodactyl\Exceptions\Repository\DuplicateDatabaseNameException; use Pterodactyl\Exceptions\Repository\DuplicateDatabaseNameException;
use Pterodactyl\Exceptions\Service\Database\TooManyDatabasesException; use Pterodactyl\Exceptions\Service\Database\TooManyDatabasesException;
use Pterodactyl\Exceptions\Service\Database\DatabaseClientFeatureNotEnabledException; use Pterodactyl\Exceptions\Service\Database\DatabaseClientFeatureNotEnabledException;
@ -36,8 +35,7 @@ class DatabaseManagementService
public function __construct( public function __construct(
protected ConnectionInterface $connection, protected ConnectionInterface $connection,
protected DynamicDatabaseConnection $dynamic, protected DynamicDatabaseConnection $dynamic,
protected Encrypter $encrypter, protected Encrypter $encrypter
protected DatabaseRepository $repository
) { ) {
} }
@ -105,26 +103,26 @@ class DatabaseManagementService
$this->dynamic->set('dynamic', $data['database_host_id']); $this->dynamic->set('dynamic', $data['database_host_id']);
$this->repository->createDatabase($database->database); $database->createDatabase($database->database);
$this->repository->createUser( $database->createUser(
$database->username, $database->username,
$database->remote, $database->remote,
$this->encrypter->decrypt($database->password), $this->encrypter->decrypt($database->password),
$database->max_connections $database->max_connections
); );
$this->repository->assignUserToDatabase($database->database, $database->username, $database->remote); $database->assignUserToDatabase($database->database, $database->username, $database->remote);
$this->repository->flush(); $database->flush();
return $database; return $database;
}); });
} catch (Exception $exception) { } catch (Exception $exception) {
try { try {
if ($database instanceof Database) { if ($database instanceof Database) {
$this->repository->dropDatabase($database->database); $database->dropDatabase($database->database);
$this->repository->dropUser($database->username, $database->remote); $database->dropUser($database->username, $database->remote);
$this->repository->flush(); $database->flush();
} }
} catch (Exception $deletionException) { } catch (Exception) {
// Do nothing here. We've already encountered an issue before this point so no // Do nothing here. We've already encountered an issue before this point so no
// reason to prioritize this error over the initial one. // reason to prioritize this error over the initial one.
} }
@ -142,9 +140,9 @@ class DatabaseManagementService
{ {
$this->dynamic->set('dynamic', $database->database_host_id); $this->dynamic->set('dynamic', $database->database_host_id);
$this->repository->dropDatabase($database->database); $database->dropDatabase($database->database);
$this->repository->dropUser($database->username, $database->remote); $database->dropUser($database->username, $database->remote);
$this->repository->flush(); $database->flush();
return $database->delete(); return $database->delete();
} }

View file

@ -7,7 +7,6 @@ use Pterodactyl\Helpers\Utilities;
use Illuminate\Database\ConnectionInterface; use Illuminate\Database\ConnectionInterface;
use Illuminate\Contracts\Encryption\Encrypter; use Illuminate\Contracts\Encryption\Encrypter;
use Pterodactyl\Extensions\DynamicDatabaseConnection; use Pterodactyl\Extensions\DynamicDatabaseConnection;
use Pterodactyl\Contracts\Repository\DatabaseRepositoryInterface;
class DatabasePasswordService class DatabasePasswordService
{ {
@ -17,8 +16,7 @@ class DatabasePasswordService
public function __construct( public function __construct(
private ConnectionInterface $connection, private ConnectionInterface $connection,
private DynamicDatabaseConnection $dynamic, private DynamicDatabaseConnection $dynamic,
private Encrypter $encrypter, private Encrypter $encrypter
private DatabaseRepositoryInterface $repository
) { ) {
} }
@ -34,14 +32,14 @@ class DatabasePasswordService
$this->connection->transaction(function () use ($database, $password) { $this->connection->transaction(function () use ($database, $password) {
$this->dynamic->set('dynamic', $database->database_host_id); $this->dynamic->set('dynamic', $database->database_host_id);
$this->repository->withoutFreshModel()->update($database->id, [ $database->update([
'password' => $this->encrypter->encrypt($password), 'password' => $this->encrypter->encrypt($password),
]); ]);
$this->repository->dropUser($database->username, $database->remote); $database->dropUser($database->username, $database->remote);
$this->repository->createUser($database->username, $database->remote, $password, $database->max_connections); $database->createUser($database->username, $database->remote, $password, $database->max_connections);
$this->repository->assignUserToDatabase($database->database, $database->username, $database->remote); $database->assignUserToDatabase($database->database, $database->username, $database->remote);
$this->repository->flush(); $database->flush();
}); });
return $password; return $password;

View file

@ -3,33 +3,25 @@
namespace Pterodactyl\Services\Databases\Hosts; namespace Pterodactyl\Services\Databases\Hosts;
use Pterodactyl\Exceptions\Service\HasActiveServersException; use Pterodactyl\Exceptions\Service\HasActiveServersException;
use Pterodactyl\Contracts\Repository\DatabaseRepositoryInterface; use Pterodactyl\Models\DatabaseHost;
use Pterodactyl\Contracts\Repository\DatabaseHostRepositoryInterface;
class HostDeletionService class HostDeletionService
{ {
/**
* HostDeletionService constructor.
*/
public function __construct(
private DatabaseRepositoryInterface $databaseRepository,
private DatabaseHostRepositoryInterface $repository
) {
}
/** /**
* Delete a specified host from the Panel if no databases are * Delete a specified host from the Panel if no databases are
* attached to it. * attached to it.
* *
* @throws \Pterodactyl\Exceptions\Service\HasActiveServersException * @throws HasActiveServersException
*/ */
public function handle(int $host): int public function handle(int $host): int
{ {
$count = $this->databaseRepository->findCountWhere([['database_host_id', '=', $host]]); /** @var DatabaseHost $host */
if ($count > 0) { $host = DatabaseHost::query()->findOrFail($host);
if ($host->databases()->count() > 0) {
throw new HasActiveServersException(trans('exceptions.databases.delete_has_databases')); throw new HasActiveServersException(trans('exceptions.databases.delete_has_databases'));
} }
return $this->repository->delete($host); return $host->delete();
} }
} }