88 lines
2.8 KiB
PHP
88 lines
2.8 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace app\common\service\iam;
|
|
|
|
use RuntimeException;
|
|
|
|
class IamHubClient
|
|
{
|
|
private array $config;
|
|
private IamHttpClient $http;
|
|
|
|
public function __construct(?array $config = null, ?IamHttpClient $http = null)
|
|
{
|
|
$this->config = $config ?? (array) config('iam_hub');
|
|
$this->http = $http ?? new IamHttpClient(null, (int) ($this->config['http_timeout_seconds'] ?? 10));
|
|
}
|
|
|
|
/** @return array<string,mixed> */
|
|
public function provisioningContext(string $subject): array
|
|
{
|
|
return $this->request(
|
|
'GET',
|
|
sprintf(
|
|
'%s/internal/v1/applications/%s/employees/%s/provisioning-context',
|
|
$this->baseUrl(),
|
|
rawurlencode($this->applicationId()),
|
|
rawurlencode($subject)
|
|
)
|
|
);
|
|
}
|
|
|
|
public function bindAccount(string $subject, int $adminId): void
|
|
{
|
|
$this->request(
|
|
'POST',
|
|
sprintf(
|
|
'%s/internal/v1/applications/%s/bindings',
|
|
$this->baseUrl(),
|
|
rawurlencode($this->applicationId())
|
|
),
|
|
[
|
|
'employeeSubject' => $subject,
|
|
'externalAccountId' => (string) $adminId,
|
|
'verificationMethod' => 'oidc-lazy-provision',
|
|
],
|
|
$this->bindingHeaders($subject, $adminId)
|
|
);
|
|
}
|
|
|
|
/** @return array<string,mixed> */
|
|
private function request(string $method, string $url, ?array $body = null, array $extraHeaders = []): array
|
|
{
|
|
$token = trim((string) ($this->config['application_token'] ?? ''));
|
|
if ($token === '') {
|
|
throw new RuntimeException('IAM Hub application credential is not configured');
|
|
}
|
|
$result = $this->http->json(
|
|
$method,
|
|
$url,
|
|
array_merge(['Authorization: Bearer ' . $token], $extraHeaders),
|
|
$body
|
|
);
|
|
if ($result['status'] < 200 || $result['status'] >= 300) {
|
|
$message = (string) ($result['body']['error'] ?? $result['body']['message'] ?? 'IAM Hub request failed');
|
|
throw new RuntimeException($message . ' (HTTP ' . $result['status'] . ')');
|
|
}
|
|
return $result['body'];
|
|
}
|
|
|
|
private function baseUrl(): string
|
|
{
|
|
return rtrim((string) ($this->config['base_url'] ?? ''), '/');
|
|
}
|
|
|
|
private function applicationId(): string
|
|
{
|
|
return (string) ($this->config['application_id'] ?? 'zyt');
|
|
}
|
|
|
|
private function bindingHeaders(string $subject, int $adminId): array
|
|
{
|
|
$requestId = hash('sha256', $this->applicationId() . ':' . $subject . ':' . $adminId);
|
|
return ['X-Request-ID: ' . $requestId, 'Idempotency-Key: ' . $requestId];
|
|
}
|
|
}
|