Files
2026-09-28 08:26:29 +07:00

97 lines
2.8 KiB
PHP

<?php
namespace App\Http\Services\vCenter;
use App\Support\TlsHttpClientFactory;
use App\Http\Facade\SignRSA;
use App\Models\Vcenter;
class Client
{
public ?string $token = null;
public string $apiUri;
private string $username;
private string $password;
public function loginServer(Vcenter $vcenterModel): bool|string
{
// console.tgs.com.vn (HAProxy) only proxies WMKS console websockets
// to ESXi hosts by ?host= — the vCenter management API must be
// called directly against the vCenter's own host.
$this->apiUri = $vcenterModel->host;
$this->username = $vcenterModel->user;
$this->password = SignRSA::DecryptFunc($vcenterModel->password);
$response = TlsHttpClientFactory::vCenter()
->withBasicAuth($this->username, $this->password)
->post("https://{$this->apiUri}/rest/com/vmware/cis/session", []);
if ($response->successful()) {
$json = $response->json();
if (isset($json['value'])) {
$this->token = $json['value'];
$vcenterModel->update(['token' => $this->token]);
return $this->token;
}
$body = $response->body();
if (!empty($body)) {
$this->token = $body;
$vcenterModel->update(['token' => $this->token]);
return $this->token;
}
}
return false;
}
public function checkApiExits(): bool
{
$response = TlsHttpClientFactory::vCenter()
->withHeaders([
'vmware-api-session-id' => $this->token
])
->get("https://$this->apiUri/rest/com/vmware/content/library")->json();
if (isset($response['type'])) {
return false;
}
return true;
}
public function getUsername(): string
{
return $this->username;
}
public function getPassword(): string
{
return $this->password;
}
public function SetConfig($data): static
{
$this->username = $data['user'] ?? $data->user;
$this->password = \App\Http\Facade\SignRSA::DecryptFunc($data['password'] ?? $data->password);
return $this;
}
public function resolveVCenterFromProduct(\App\Models\ModuleVmware $product): ?\App\Models\vCenter
{
if ($product->vCenter) {
return $product->vCenter;
}
if ($product->ipAddress?->host?->datacenter?->vCenter) {
return $product->ipAddress->host->datacenter->vCenter;
}
$service = $product->services()->first();
if ($service) {
$service->load('vmware.vCenter');
if ($service->vmware?->vCenter) {
return $service->vmware->vCenter;
}
}
return null;
}
}