1
0
Fork 0
mirror of https://github.com/archtechx/tenancy.git synced 2025-12-12 15:34:03 +00:00

Test ecnrypted casts (#1284)

This commit is contained in:
lukinovec 2025-02-14 08:48:16 +01:00 committed by GitHub
parent 30ee4e9529
commit fffaf7c58c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -405,6 +405,42 @@ test('tenant database can be created by using the username and password from ten
expect($manager->databaseExists($name))->toBeTrue(); expect($manager->databaseExists($name))->toBeTrue();
}); });
test('decrypted password can be used to connect to a tenant db while the password is saved as encrypted', function (string|null $tenantDbPassword) {
config([
'tenancy.database.managers.mysql' => PermissionControlledMySQLDatabaseManager::class,
'tenancy.database.template_tenant_connection' => 'mysql',
]);
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
return $event->tenant;
})->toListener());
// Create a tenant, either with a specific password, or with a password generated by the DB manager
$tenant = TenantWithEncryptedPassword::create([
'tenancy_db_name' => $name = 'foo' . Str::random(8),
'tenancy_db_username' => 'user' . Str::random(4),
'tenancy_db_password' => $tenantDbPassword,
]);
$decryptedPassword = $tenant->tenancy_db_password;
$encryptedPassword = $tenant->getAttributes()['tenancy_db_password']; // Password encrypted using the TenantWithEncryptedPassword model's encrypted cast
expect($decryptedPassword)->not()->toBe($encryptedPassword);
$passwordSavedInDatabase = json_decode(DB::select('SELECT data FROM tenants LIMIT 1')[0]->data)->tenancy_db_password;
expect($encryptedPassword)->toBe($passwordSavedInDatabase);
app(DatabaseManager::class)->connectToTenant($tenant);
// Check if we got connected to the tenant DB
expect(config('database.default'))->toBe('tenant');
expect(config('database.connections.tenant.database'))->toBe($name);
// Check if the decrypted password is used to connect to the tenant DB
expect(config('database.connections.tenant.password'))->toBe($decryptedPassword);
})->with([
'decrypted' . Str::random(8), // Use this password as the tenant DB password
null, // Let the DB manager generate the tenant DB password
]);
test('path used by sqlite manager can be customized', function () { test('path used by sqlite manager can be customized', function () {
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) { Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
return $event->tenant; return $event->tenant;
@ -529,3 +565,13 @@ function createUsersTable()
$table->timestamps(); $table->timestamps();
}); });
} }
class TenantWithEncryptedPassword extends Tenant
{
protected function casts(): array
{
return [
'tenancy_db_password' => 'encrypted',
];
}
}