Replace with helper

This commit is contained in:
Lance Pioch 2024-03-19 05:11:41 -04:00
parent d9cfb62a12
commit d58496a355
20 changed files with 28 additions and 125 deletions

View File

@ -3,7 +3,6 @@
namespace App\Extensions; namespace App\Extensions;
use App\Models\DatabaseHost; use App\Models\DatabaseHost;
use Illuminate\Contracts\Encryption\Encrypter;
class DynamicDatabaseConnection class DynamicDatabaseConnection
{ {
@ -11,14 +10,6 @@ class DynamicDatabaseConnection
public const DB_COLLATION = 'utf8_unicode_ci'; public const DB_COLLATION = 'utf8_unicode_ci';
public const DB_DRIVER = 'mysql'; public const DB_DRIVER = 'mysql';
/**
* DynamicDatabaseConnection constructor.
*/
public function __construct(
protected Encrypter $encrypter,
) {
}
/** /**
* Adds a dynamic database connection entry to the runtime config. * Adds a dynamic database connection entry to the runtime config.
*/ */
@ -34,7 +25,7 @@ class DynamicDatabaseConnection
'port' => $host->port, 'port' => $host->port,
'database' => $database, 'database' => $database,
'username' => $host->username, 'username' => $host->username,
'password' => $this->encrypter->decrypt($host->password), 'password' => decrypt($host->password),
'charset' => self::DB_CHARSET, 'charset' => self::DB_CHARSET,
'collation' => self::DB_COLLATION, 'collation' => self::DB_COLLATION,
]); ]);

View File

@ -7,7 +7,6 @@ use App\Models\Node;
use App\Models\ApiKey; use App\Models\ApiKey;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use Illuminate\Contracts\Encryption\Encrypter;
use App\Services\Api\KeyCreationService; use App\Services\Api\KeyCreationService;
class NodeAutoDeployController extends Controller class NodeAutoDeployController extends Controller
@ -16,7 +15,6 @@ class NodeAutoDeployController extends Controller
* NodeAutoDeployController constructor. * NodeAutoDeployController constructor.
*/ */
public function __construct( public function __construct(
private Encrypter $encrypter,
private KeyCreationService $keyCreationService private KeyCreationService $keyCreationService
) { ) {
} }
@ -58,7 +56,7 @@ class NodeAutoDeployController extends Controller
return new JsonResponse([ return new JsonResponse([
'node' => $node->id, 'node' => $node->id,
'token' => $key->identifier . $this->encrypter->decrypt($key->token), 'token' => $key->identifier . decrypt($key->token),
]); ]);
} }
} }

View File

@ -11,7 +11,6 @@ use App\Notifications\MailTested;
use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\Notification;
use App\Exceptions\DisplayException; use App\Exceptions\DisplayException;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use Illuminate\Contracts\Encryption\Encrypter;
use App\Providers\SettingsServiceProvider; use App\Providers\SettingsServiceProvider;
use App\Http\Requests\Admin\Settings\MailSettingsFormRequest; use App\Http\Requests\Admin\Settings\MailSettingsFormRequest;
@ -21,7 +20,6 @@ class MailController extends Controller
* MailController constructor. * MailController constructor.
*/ */
public function __construct( public function __construct(
private Encrypter $encrypter,
private Kernel $kernel, private Kernel $kernel,
) { ) {
} }
@ -56,7 +54,7 @@ class MailController extends Controller
foreach ($values as $key => $value) { foreach ($values as $key => $value) {
if (in_array($key, SettingsServiceProvider::getEncryptedKeys()) && !empty($value)) { if (in_array($key, SettingsServiceProvider::getEncryptedKeys()) && !empty($value)) {
$value = $this->encrypter->encrypt($value); $value = encrypt($value);
} }
Setting::set('settings::' . $key, $value); Setting::set('settings::' . $key, $value);

View File

@ -8,7 +8,6 @@ use App\Models\User;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use PragmaRX\Google2FA\Google2FA; use PragmaRX\Google2FA\Google2FA;
use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Event;
use Illuminate\Contracts\Encryption\Encrypter;
use App\Events\Auth\ProvidedAuthenticationToken; use App\Events\Auth\ProvidedAuthenticationToken;
use App\Http\Requests\Auth\LoginCheckpointRequest; use App\Http\Requests\Auth\LoginCheckpointRequest;
use Illuminate\Contracts\Validation\Factory as ValidationFactory; use Illuminate\Contracts\Validation\Factory as ValidationFactory;
@ -21,7 +20,6 @@ class LoginCheckpointController extends AbstractLoginController
* LoginCheckpointController constructor. * LoginCheckpointController constructor.
*/ */
public function __construct( public function __construct(
private Encrypter $encrypter,
private Google2FA $google2FA, private Google2FA $google2FA,
private ValidationFactory $validation private ValidationFactory $validation
) { ) {
@ -67,7 +65,7 @@ class LoginCheckpointController extends AbstractLoginController
return $this->sendLoginResponse($user, $request); return $this->sendLoginResponse($user, $request);
} }
} else { } else {
$decrypted = $this->encrypter->decrypt($user->totp_secret); $decrypted = decrypt($user->totp_secret);
if ($this->google2FA->verifyKey($decrypted, (string) $request->input('authentication_code'), config('panel.auth.2fa.window'))) { if ($this->google2FA->verifyKey($decrypted, (string) $request->input('authentication_code'), config('panel.auth.2fa.window'))) {
Event::dispatch(new ProvidedAuthenticationToken($user)); Event::dispatch(new ProvidedAuthenticationToken($user));

View File

@ -4,7 +4,6 @@ namespace App\Http\Middleware\Api\Daemon;
use App\Models\Node; use App\Models\Node;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Contracts\Encryption\Encrypter;
use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
@ -18,13 +17,6 @@ class DaemonAuthenticate
'daemon.configuration', 'daemon.configuration',
]; ];
/**
* DaemonAuthenticate constructor.
*/
public function __construct(private Encrypter $encrypter)
{
}
/** /**
* Check if a request from the daemon can be properly attributed back to a single node instance. * Check if a request from the daemon can be properly attributed back to a single node instance.
* *
@ -49,7 +41,7 @@ class DaemonAuthenticate
/** @var Node $node */ /** @var Node $node */
$node = Node::query()->where('daemon_token_id', $parts[0])->firstOrFail(); $node = Node::query()->where('daemon_token_id', $parts[0])->firstOrFail();
if (hash_equals((string) $this->encrypter->decrypt($node->daemon_token), $parts[1])) { if (hash_equals((string) decrypt($node->daemon_token), $parts[1])) {
$request->attributes->set('node', $node); $request->attributes->set('node', $node);
return $next($request); return $next($request);

View File

@ -4,9 +4,7 @@ namespace App\Models;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Symfony\Component\Yaml\Yaml; use Symfony\Component\Yaml\Yaml;
use Illuminate\Container\Container;
use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Encryption\Encrypter;
use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough; use Illuminate\Database\Eloquent\Relations\HasManyThrough;
@ -136,7 +134,7 @@ class Node extends Model
'debug' => false, 'debug' => false,
'uuid' => $this->uuid, 'uuid' => $this->uuid,
'token_id' => $this->daemon_token_id, 'token_id' => $this->daemon_token_id,
'token' => Container::getInstance()->make(Encrypter::class)->decrypt($this->daemon_token), 'token' => decrypt($this->daemon_token),
'api' => [ 'api' => [
'host' => '0.0.0.0', 'host' => '0.0.0.0',
'port' => $this->daemonListen, 'port' => $this->daemonListen,
@ -179,7 +177,7 @@ class Node extends Model
*/ */
public function getDecryptedKey(): string public function getDecryptedKey(): string
{ {
return (string) Container::getInstance()->make(Encrypter::class)->decrypt( return (string) decrypt(
$this->daemon_token $this->daemon_token
); );
} }

View File

@ -3,11 +3,10 @@
namespace App\Providers; namespace App\Providers;
use App\Models\Setting; use App\Models\Setting;
use Exception;
use Psr\Log\LoggerInterface as Log; use Psr\Log\LoggerInterface as Log;
use Illuminate\Database\QueryException; use Illuminate\Database\QueryException;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Encryption\Encrypter;
use Illuminate\Contracts\Encryption\DecryptException;
class SettingsServiceProvider extends ServiceProvider class SettingsServiceProvider extends ServiceProvider
{ {
@ -56,7 +55,7 @@ class SettingsServiceProvider extends ServiceProvider
/** /**
* Boot the service provider. * Boot the service provider.
*/ */
public function boot(Encrypter $encrypter, Log $log): void public function boot(Log $log): void
{ {
// Only set the email driver settings from the database if we // Only set the email driver settings from the database if we
// are configured using SMTP as the driver. // are configured using SMTP as the driver.
@ -78,8 +77,9 @@ class SettingsServiceProvider extends ServiceProvider
$value = array_get($values, 'settings::' . $key, config(str_replace(':', '.', $key))); $value = array_get($values, 'settings::' . $key, config(str_replace(':', '.', $key)));
if (in_array($key, self::$encrypted)) { if (in_array($key, self::$encrypted)) {
try { try {
$value = $encrypter->decrypt($value); $value = decrypt($value);
} catch (DecryptException $exception) { } catch (Exception) {
// ignore
} }
} }

View File

@ -3,19 +3,11 @@
namespace App\Services\Api; namespace App\Services\Api;
use App\Models\ApiKey; use App\Models\ApiKey;
use Illuminate\Contracts\Encryption\Encrypter;
class KeyCreationService class KeyCreationService
{ {
private int $keyType = ApiKey::TYPE_NONE; private int $keyType = ApiKey::TYPE_NONE;
/**
* ApiKeyService constructor.
*/
public function __construct(private Encrypter $encrypter)
{
}
/** /**
* Set the type of key that should be created. By default, an orphaned key will be * Set the type of key that should be created. By default, an orphaned key will be
* created. These keys cannot be used for anything, and will not render in the UI. * created. These keys cannot be used for anything, and will not render in the UI.
@ -39,7 +31,7 @@ class KeyCreationService
$data = array_merge($data, [ $data = array_merge($data, [
'key_type' => $this->keyType, 'key_type' => $this->keyType,
'identifier' => ApiKey::generateTokenIdentifier($this->keyType), 'identifier' => ApiKey::generateTokenIdentifier($this->keyType),
'token' => $this->encrypter->encrypt(str_random(ApiKey::KEY_LENGTH)), 'token' => encrypt(str_random(ApiKey::KEY_LENGTH)),
]); ]);
if ($this->keyType === ApiKey::TYPE_APPLICATION) { if ($this->keyType === ApiKey::TYPE_APPLICATION) {

View File

@ -2,12 +2,10 @@
namespace App\Services\Databases; namespace App\Services\Databases;
use Exception;
use App\Models\Server; use App\Models\Server;
use App\Models\Database; use App\Models\Database;
use App\Helpers\Utilities; use App\Helpers\Utilities;
use Illuminate\Database\ConnectionInterface; use Illuminate\Database\ConnectionInterface;
use Illuminate\Contracts\Encryption\Encrypter;
use App\Extensions\DynamicDatabaseConnection; use App\Extensions\DynamicDatabaseConnection;
use App\Exceptions\Repository\DuplicateDatabaseNameException; use App\Exceptions\Repository\DuplicateDatabaseNameException;
use App\Exceptions\Service\Database\TooManyDatabasesException; use App\Exceptions\Service\Database\TooManyDatabasesException;
@ -34,7 +32,6 @@ class DatabaseManagementService
public function __construct( public function __construct(
protected ConnectionInterface $connection, protected ConnectionInterface $connection,
protected DynamicDatabaseConnection $dynamic, protected DynamicDatabaseConnection $dynamic,
protected Encrypter $encrypter,
) { ) {
} }
@ -89,7 +86,7 @@ class DatabaseManagementService
$data = array_merge($data, [ $data = array_merge($data, [
'server_id' => $server->id, 'server_id' => $server->id,
'username' => sprintf('u%d_%s', $server->id, str_random(10)), 'username' => sprintf('u%d_%s', $server->id, str_random(10)),
'password' => $this->encrypter->encrypt( 'password' => encrypt(
Utilities::randomStringWithSpecialCharacters(24) Utilities::randomStringWithSpecialCharacters(24)
), ),
]); ]);
@ -103,7 +100,7 @@ class DatabaseManagementService
$database->createUser( $database->createUser(
$database->username, $database->username,
$database->remote, $database->remote,
$this->encrypter->decrypt($database->password), decrypt($database->password),
$database->max_connections $database->max_connections
); );
$database->assignUserToDatabase($database->database, $database->username, $database->remote); $database->assignUserToDatabase($database->database, $database->username, $database->remote);

View File

@ -5,7 +5,6 @@ namespace App\Services\Databases;
use App\Models\Database; use App\Models\Database;
use App\Helpers\Utilities; use App\Helpers\Utilities;
use Illuminate\Database\ConnectionInterface; use Illuminate\Database\ConnectionInterface;
use Illuminate\Contracts\Encryption\Encrypter;
use App\Extensions\DynamicDatabaseConnection; use App\Extensions\DynamicDatabaseConnection;
class DatabasePasswordService class DatabasePasswordService
@ -16,7 +15,6 @@ class DatabasePasswordService
public function __construct( public function __construct(
private ConnectionInterface $connection, private ConnectionInterface $connection,
private DynamicDatabaseConnection $dynamic, private DynamicDatabaseConnection $dynamic,
private Encrypter $encrypter,
) { ) {
} }
@ -35,7 +33,7 @@ class DatabasePasswordService
$this->dynamic->set('dynamic', $database->database_host_id); $this->dynamic->set('dynamic', $database->database_host_id);
$database->update([ $database->update([
'password' => $this->encrypter->encrypt($password), 'password' => encrypt($password),
]); ]);
$database->dropUser($database->username, $database->remote); $database->dropUser($database->username, $database->remote);

View File

@ -5,7 +5,6 @@ namespace App\Services\Databases\Hosts;
use App\Models\DatabaseHost; use App\Models\DatabaseHost;
use Illuminate\Database\DatabaseManager; use Illuminate\Database\DatabaseManager;
use Illuminate\Database\ConnectionInterface; use Illuminate\Database\ConnectionInterface;
use Illuminate\Contracts\Encryption\Encrypter;
use App\Extensions\DynamicDatabaseConnection; use App\Extensions\DynamicDatabaseConnection;
class HostCreationService class HostCreationService
@ -17,7 +16,6 @@ class HostCreationService
private ConnectionInterface $connection, private ConnectionInterface $connection,
private DatabaseManager $databaseManager, private DatabaseManager $databaseManager,
private DynamicDatabaseConnection $dynamic, private DynamicDatabaseConnection $dynamic,
private Encrypter $encrypter,
) { ) {
} }
@ -30,7 +28,7 @@ class HostCreationService
{ {
return $this->connection->transaction(function () use ($data) { return $this->connection->transaction(function () use ($data) {
$host = DatabaseHost::query()->create([ $host = DatabaseHost::query()->create([
'password' => $this->encrypter->encrypt(array_get($data, 'password')), 'password' => encrypt(array_get($data, 'password')),
'name' => array_get($data, 'name'), 'name' => array_get($data, 'name'),
'host' => array_get($data, 'host'), 'host' => array_get($data, 'host'),
'port' => array_get($data, 'port'), 'port' => array_get($data, 'port'),

View File

@ -5,7 +5,6 @@ namespace App\Services\Databases\Hosts;
use App\Models\DatabaseHost; use App\Models\DatabaseHost;
use Illuminate\Database\DatabaseManager; use Illuminate\Database\DatabaseManager;
use Illuminate\Database\ConnectionInterface; use Illuminate\Database\ConnectionInterface;
use Illuminate\Contracts\Encryption\Encrypter;
use App\Extensions\DynamicDatabaseConnection; use App\Extensions\DynamicDatabaseConnection;
class HostUpdateService class HostUpdateService
@ -17,7 +16,6 @@ class HostUpdateService
private ConnectionInterface $connection, private ConnectionInterface $connection,
private DatabaseManager $databaseManager, private DatabaseManager $databaseManager,
private DynamicDatabaseConnection $dynamic, private DynamicDatabaseConnection $dynamic,
private Encrypter $encrypter,
) { ) {
} }
@ -29,7 +27,7 @@ class HostUpdateService
public function handle(int $hostId, array $data): DatabaseHost public function handle(int $hostId, array $data): DatabaseHost
{ {
if (!empty(array_get($data, 'password'))) { if (!empty(array_get($data, 'password'))) {
$data['password'] = $this->encrypter->encrypt($data['password']); $data['password'] = encrypt($data['password']);
} else { } else {
unset($data['password']); unset($data['password']);
} }

View File

@ -5,7 +5,6 @@ namespace App\Services\Nodes;
use Ramsey\Uuid\Uuid; use Ramsey\Uuid\Uuid;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use App\Models\Node; use App\Models\Node;
use Illuminate\Contracts\Encryption\Encrypter;
class NodeCreationService class NodeCreationService
{ {
@ -17,7 +16,7 @@ class NodeCreationService
public function handle(array $data): Node public function handle(array $data): Node
{ {
$data['uuid'] = Uuid::uuid4()->toString(); $data['uuid'] = Uuid::uuid4()->toString();
$data['daemon_token'] = app(Encrypter::class)->encrypt(Str::random(Node::DAEMON_TOKEN_LENGTH)); $data['daemon_token'] = encrypt(Str::random(Node::DAEMON_TOKEN_LENGTH));
$data['daemon_token_id'] = Str::random(Node::DAEMON_TOKEN_ID_LENGTH); $data['daemon_token_id'] = Str::random(Node::DAEMON_TOKEN_ID_LENGTH);
return Node::query()->create($data); return Node::query()->create($data);

View File

@ -5,7 +5,6 @@ namespace App\Services\Nodes;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use App\Models\Node; use App\Models\Node;
use Illuminate\Database\ConnectionInterface; use Illuminate\Database\ConnectionInterface;
use Illuminate\Contracts\Encryption\Encrypter;
use App\Repositories\Daemon\DaemonConfigurationRepository; use App\Repositories\Daemon\DaemonConfigurationRepository;
use App\Exceptions\Http\Connection\DaemonConnectionException; use App\Exceptions\Http\Connection\DaemonConnectionException;
use App\Exceptions\Service\Node\ConfigurationNotPersistedException; use App\Exceptions\Service\Node\ConfigurationNotPersistedException;
@ -18,7 +17,6 @@ class NodeUpdateService
public function __construct( public function __construct(
private ConnectionInterface $connection, private ConnectionInterface $connection,
private DaemonConfigurationRepository $configurationRepository, private DaemonConfigurationRepository $configurationRepository,
private Encrypter $encrypter,
) { ) {
} }
@ -30,7 +28,7 @@ class NodeUpdateService
public function handle(Node $node, array $data, bool $resetToken = false): Node public function handle(Node $node, array $data, bool $resetToken = false): Node
{ {
if ($resetToken) { if ($resetToken) {
$data['daemon_token'] = $this->encrypter->encrypt(Str::random(Node::DAEMON_TOKEN_LENGTH)); $data['daemon_token'] = encrypt(Str::random(Node::DAEMON_TOKEN_LENGTH));
$data['daemon_token_id'] = Str::random(Node::DAEMON_TOKEN_ID_LENGTH); $data['daemon_token_id'] = Str::random(Node::DAEMON_TOKEN_ID_LENGTH);
} }

View File

@ -8,7 +8,6 @@ use Illuminate\Support\Str;
use App\Models\User; use App\Models\User;
use PragmaRX\Google2FA\Google2FA; use PragmaRX\Google2FA\Google2FA;
use Illuminate\Database\ConnectionInterface; use Illuminate\Database\ConnectionInterface;
use Illuminate\Contracts\Encryption\Encrypter;
use App\Exceptions\Service\User\TwoFactorAuthenticationTokenInvalid; use App\Exceptions\Service\User\TwoFactorAuthenticationTokenInvalid;
class ToggleTwoFactorService class ToggleTwoFactorService
@ -18,7 +17,6 @@ class ToggleTwoFactorService
*/ */
public function __construct( public function __construct(
private ConnectionInterface $connection, private ConnectionInterface $connection,
private Encrypter $encrypter,
private Google2FA $google2FA, private Google2FA $google2FA,
) { ) {
} }
@ -34,7 +32,7 @@ class ToggleTwoFactorService
*/ */
public function handle(User $user, string $token, bool $toggleState = null): array public function handle(User $user, string $token, bool $toggleState = null): array
{ {
$secret = $this->encrypter->decrypt($user->totp_secret); $secret = decrypt($user->totp_secret);
$isValidToken = $this->google2FA->verifyKey($secret, $token, config()->get('panel.auth.2fa.window')); $isValidToken = $this->google2FA->verifyKey($secret, $token, config()->get('panel.auth.2fa.window'));

View File

@ -3,20 +3,11 @@
namespace App\Services\Users; namespace App\Services\Users;
use App\Models\User; use App\Models\User;
use Illuminate\Contracts\Encryption\Encrypter;
class TwoFactorSetupService class TwoFactorSetupService
{ {
public const VALID_BASE32_CHARACTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; public const VALID_BASE32_CHARACTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
/**
* TwoFactorSetupService constructor.
*/
public function __construct(
private Encrypter $encrypter,
) {
}
/** /**
* Generate a 2FA token and store it in the database before returning the * Generate a 2FA token and store it in the database before returning the
* QR code URL. This URL will need to be attached to a QR generating service in * QR code URL. This URL will need to be attached to a QR generating service in
@ -35,7 +26,7 @@ class TwoFactorSetupService
throw new \RuntimeException($exception->getMessage(), 0, $exception); throw new \RuntimeException($exception->getMessage(), 0, $exception);
} }
$user->totp_secret = $this->encrypter->encrypt($secret); $user->totp_secret = encrypt($secret);
$user->save(); $user->save();
$company = urlencode(preg_replace('/\s/', '', config('app.name'))); $company = urlencode(preg_replace('/\s/', '', config('app.name')));

View File

@ -7,22 +7,11 @@ use League\Fractal\Resource\Item;
use App\Models\DatabaseHost; use App\Models\DatabaseHost;
use League\Fractal\Resource\NullResource; use League\Fractal\Resource\NullResource;
use App\Services\Acl\Api\AdminAcl; use App\Services\Acl\Api\AdminAcl;
use Illuminate\Contracts\Encryption\Encrypter;
class ServerDatabaseTransformer extends BaseTransformer class ServerDatabaseTransformer extends BaseTransformer
{ {
protected array $availableIncludes = ['password', 'host']; protected array $availableIncludes = ['password', 'host'];
private Encrypter $encrypter;
/**
* Perform dependency injection.
*/
public function handle(Encrypter $encrypter)
{
$this->encrypter = $encrypter;
}
/** /**
* Return the resource name for the JSONAPI output. * Return the resource name for the JSONAPI output.
*/ */
@ -56,7 +45,7 @@ class ServerDatabaseTransformer extends BaseTransformer
{ {
return $this->item($model, function (Database $model) { return $this->item($model, function (Database $model) {
return [ return [
'password' => $this->encrypter->decrypt($model->password), 'password' => decrypt($model->password),
]; ];
}, 'database_password'); }, 'database_password');
} }

View File

@ -6,23 +6,19 @@ use App\Models\Database;
use League\Fractal\Resource\Item; use League\Fractal\Resource\Item;
use App\Models\Permission; use App\Models\Permission;
use League\Fractal\Resource\NullResource; use League\Fractal\Resource\NullResource;
use Illuminate\Contracts\Encryption\Encrypter;
use App\Contracts\Extensions\HashidsInterface; use App\Contracts\Extensions\HashidsInterface;
class DatabaseTransformer extends BaseClientTransformer class DatabaseTransformer extends BaseClientTransformer
{ {
protected array $availableIncludes = ['password']; protected array $availableIncludes = ['password'];
private Encrypter $encrypter;
private HashidsInterface $hashids; private HashidsInterface $hashids;
/** /**
* Handle dependency injection. * Handle dependency injection.
*/ */
public function handle(Encrypter $encrypter, HashidsInterface $hashids) public function handle(HashidsInterface $hashids)
{ {
$this->encrypter = $encrypter;
$this->hashids = $hashids; $this->hashids = $hashids;
} }
@ -59,7 +55,7 @@ class DatabaseTransformer extends BaseClientTransformer
return $this->item($database, function (Database $model) { return $this->item($database, function (Database $model) {
return [ return [
'password' => $this->encrypter->decrypt($model->password), 'password' => decrypt($model->password),
]; ];
}, 'database_password'); }, 'database_password');
} }

View File

@ -2,11 +2,9 @@
use Ramsey\Uuid\Uuid; use Ramsey\Uuid\Uuid;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Container\Container;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Migrations\Migration;
use Illuminate\Contracts\Encryption\Encrypter;
class StoreNodeTokensAsEncryptedValue extends Migration class StoreNodeTokensAsEncryptedValue extends Migration
{ {
@ -33,14 +31,11 @@ class StoreNodeTokensAsEncryptedValue extends Migration
$table->text('daemon_token')->change(); $table->text('daemon_token')->change();
}); });
/** @var \Illuminate\Contracts\Encryption\Encrypter $encrypter */
$encrypter = Container::getInstance()->make(Encrypter::class);
foreach (DB::select('SELECT id, daemon_token FROM nodes') as $datum) { foreach (DB::select('SELECT id, daemon_token FROM nodes') as $datum) {
DB::update('UPDATE nodes SET uuid = ?, daemon_token_id = ?, daemon_token = ? WHERE id = ?', [ DB::update('UPDATE nodes SET uuid = ?, daemon_token_id = ?, daemon_token = ? WHERE id = ?', [
Uuid::uuid4()->toString(), Uuid::uuid4()->toString(),
substr($datum->daemon_token, 0, 16), substr($datum->daemon_token, 0, 16),
$encrypter->encrypt(substr($datum->daemon_token, 16)), encrypt(substr($datum->daemon_token, 16)),
$datum->id, $datum->id,
]); ]);
} }
@ -59,12 +54,9 @@ class StoreNodeTokensAsEncryptedValue extends Migration
public function down() public function down()
{ {
DB::transaction(function () { DB::transaction(function () {
/** @var \Illuminate\Contracts\Encryption\Encrypter $encrypter */
$encrypter = Container::getInstance()->make(Encrypter::class);
foreach (DB::select('SELECT id, daemon_token_id, daemon_token FROM nodes') as $datum) { foreach (DB::select('SELECT id, daemon_token_id, daemon_token FROM nodes') as $datum) {
DB::update('UPDATE nodes SET daemon_token = ? WHERE id = ?', [ DB::update('UPDATE nodes SET daemon_token = ? WHERE id = ?', [
$datum->daemon_token_id . $encrypter->decrypt($datum->daemon_token), $datum->daemon_token_id . decrypt($datum->daemon_token),
$datum->id, $datum->id,
]); ]);
} }

View File

@ -5,28 +5,13 @@ namespace App\Tests\Integration\Api\Daemon;
use App\Http\Middleware\Api\Daemon\DaemonAuthenticate; use App\Http\Middleware\Api\Daemon\DaemonAuthenticate;
use App\Models\Node; use App\Models\Node;
use App\Tests\Unit\Http\Middleware\MiddlewareTestCase; use App\Tests\Unit\Http\Middleware\MiddlewareTestCase;
use Illuminate\Contracts\Encryption\Encrypter;
use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Database\Eloquent\ModelNotFoundException;
use Mockery as m;
use Mockery\MockInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\HttpException;
class DaemonAuthenticateTest extends MiddlewareTestCase class DaemonAuthenticateTest extends MiddlewareTestCase
{ {
private MockInterface $encrypter;
/**
* Setup tests.
*/
public function setUp(): void
{
parent::setUp();
$this->encrypter = m::mock(Encrypter::class);
}
/** /**
* Test that if we are accessing the daemon configuration route this middleware is not * Test that if we are accessing the daemon configuration route this middleware is not
* applied in order to allow an unauthenticated request to use a token to grab data. * applied in order to allow an unauthenticated request to use a token to grab data.
@ -86,8 +71,6 @@ class DaemonAuthenticateTest extends MiddlewareTestCase
$this->request->expects('route->getName')->withNoArgs()->andReturn('random.route'); $this->request->expects('route->getName')->withNoArgs()->andReturn('random.route');
$this->request->expects('bearerToken')->withNoArgs()->andReturn($node->daemon_token_id . '.random_string_123'); $this->request->expects('bearerToken')->withNoArgs()->andReturn($node->daemon_token_id . '.random_string_123');
$this->encrypter->expects('decrypt')->with($node->daemon_token)->andReturns(decrypt($node->daemon_token));
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions()); $this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
} }
@ -116,7 +99,6 @@ class DaemonAuthenticateTest extends MiddlewareTestCase
$this->request->expects('route->getName')->withNoArgs()->andReturn('random.route'); $this->request->expects('route->getName')->withNoArgs()->andReturn('random.route');
$this->request->expects('bearerToken')->withNoArgs()->andReturn($node->daemon_token_id . '.the_same'); $this->request->expects('bearerToken')->withNoArgs()->andReturn($node->daemon_token_id . '.the_same');
$this->encrypter->expects('decrypt')->with($node->daemon_token)->andReturns(decrypt($node->daemon_token));
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions()); $this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
$this->assertRequestHasAttribute('node'); $this->assertRequestHasAttribute('node');
@ -147,6 +129,6 @@ class DaemonAuthenticateTest extends MiddlewareTestCase
*/ */
private function getMiddleware(): DaemonAuthenticate private function getMiddleware(): DaemonAuthenticate
{ {
return new DaemonAuthenticate($this->encrypter); return new DaemonAuthenticate();
} }
} }