69 lines
2.2 KiB
PHP
69 lines
2.2 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Services\Onboarding;
|
|
|
|
use App\Models\ProviderConnection;
|
|
use App\Models\ProviderCredential;
|
|
use App\Models\Tenant;
|
|
use App\Services\Providers\CredentialManager;
|
|
use Illuminate\Support\Arr;
|
|
use InvalidArgumentException;
|
|
use RuntimeException;
|
|
|
|
final class LegacyTenantCredentialMigrator
|
|
{
|
|
public function __construct(private readonly CredentialManager $credentials) {}
|
|
|
|
/**
|
|
* @return array{migrated: bool, message: string}
|
|
*/
|
|
public function migrate(Tenant $tenant, ProviderConnection $connection): array
|
|
{
|
|
if ((int) $connection->tenant_id !== (int) $tenant->getKey()) {
|
|
throw new InvalidArgumentException('Provider connection does not belong to the tenant.');
|
|
}
|
|
|
|
$clientId = trim((string) ($tenant->app_client_id ?? ''));
|
|
$clientSecret = trim((string) ($tenant->app_client_secret ?? ''));
|
|
|
|
if ($clientId === '' || $clientSecret === '') {
|
|
return [
|
|
'migrated' => false,
|
|
'message' => 'No legacy tenant credentials found to migrate.',
|
|
];
|
|
}
|
|
|
|
$existing = $connection->credential;
|
|
|
|
if ($existing instanceof ProviderCredential) {
|
|
if ($existing->type !== 'client_secret') {
|
|
throw new RuntimeException('Provider connection has unsupported credential type.');
|
|
}
|
|
|
|
$payload = $existing->payload;
|
|
$existingClientId = trim((string) Arr::get(is_array($payload) ? $payload : [], 'client_id'));
|
|
$existingClientSecret = trim((string) Arr::get(is_array($payload) ? $payload : [], 'client_secret'));
|
|
|
|
if ($existingClientId !== '' && $existingClientSecret !== '') {
|
|
return [
|
|
'migrated' => false,
|
|
'message' => 'Provider credentials already exist for this connection.',
|
|
];
|
|
}
|
|
}
|
|
|
|
$this->credentials->upsertClientSecretCredential(
|
|
connection: $connection,
|
|
clientId: $clientId,
|
|
clientSecret: $clientSecret,
|
|
);
|
|
|
|
return [
|
|
'migrated' => true,
|
|
'message' => 'Legacy tenant credentials migrated to the provider connection.',
|
|
];
|
|
}
|
|
}
|