update rm deadcode
This commit is contained in:
+30
-28
@@ -1,6 +1,7 @@
|
||||
APP_NAME="Thế Giới Số"
|
||||
APP_ENV=local
|
||||
APP_KEY=base64:sYMyAlCRrCeWx98l2YZqmH6wH8boVHiD2Wf6PVro9To=
|
||||
APP_KEY=
|
||||
APP_PREVIOUS_KEYS=
|
||||
APP_DEBUG=false
|
||||
APP_URL=https://dev.tgs.com.vn
|
||||
APP_LOCALE=vi
|
||||
@@ -9,32 +10,35 @@ LOG_CHANNEL=stack
|
||||
LOG_DEPRECATIONS_CHANNEL=null
|
||||
LOG_LEVEL=debug
|
||||
|
||||
|
||||
DB_CONNECTION=mysql
|
||||
DB_HOST=localhost
|
||||
DB_PORT=3306
|
||||
DB_DATABASE=portal_dev
|
||||
DB_USERNAME=portal_dev
|
||||
DB_PASSWORD="admin@123!@#dev"
|
||||
DB_PASSWORD=
|
||||
|
||||
#Config Custom SignRSA
|
||||
RSA_KEY=RXfUFoCkxItIZXffLxyEJe8EhDhCz0Nq
|
||||
RSA_PUBLIC="-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDhm9x8DFf8D4pVBgPi6N4o0Aw7\nfX90vxjAQ+ekRIVu/+5qWw/mMHbaHtVNuxmU8es1v3iN0k3QPqxNqZuXLYWWzxFR\n5XGpC9GKF1BBZxzDPV5HS4MI9kHwjAWh4XdatEEW/V4pSdZPBR5bP4PcJq+SE+4m\nKiR7HLvR6Yd3Il5AfwIDAQAB\n-----END PUBLIC KEY-----"
|
||||
RSA_PRIVATE="-----BEGIN RSA PRIVATE KEY-----\nMIICXQIBAAKBgQDhm9x8DFf8D4pVBgPi6N4o0Aw7fX90vxjAQ+ekRIVu/+5qWw/m\nMHbaHtVNuxmU8es1v3iN0k3QPqxNqZuXLYWWzxFR5XGpC9GKF1BBZxzDPV5HS4MI\n9kHwjAWh4XdatEEW/V4pSdZPBR5bP4PcJq+SE+4mKiR7HLvR6Yd3Il5AfwIDAQAB\nAoGAJcHH7JrEPtL6+6++BsOiKoJnCa2/HvK8WbEDm2I8Uo9Sf0ouJwAFZAu09wVR\nCrRSAPTCYDnJ/AgBHh48g9iCeqJE4U8coaXe2WXrR+Ys/UTxY1A6K7+RWzqbYNSL\n/Dnjf2vZmPNM0B2n/R9E5O2UBu2cHsBxhtSVJQwyQeo458ECQQD2x8yn6P2+g+P5\nyh22VjoxIE2FA2FDEuZPIARQaJWtOgqmMVb+/Id+/S34sRxXXoDF4vT9kIfKnrI6\nSBkcA271AkEA6gmTtjTP13fdpeknk+fg80CVd2LOf4dLr5Qfh2wdNhaz2Rymq9At\nO0Abvegf6l6X5ThHGeYgXZkSNYTfgeahIwJAPcT9APpcqRcyNQ/WKBGlNy6yuJyD\n99n/M8b7zXSgIl/o0nh/Igvrjmmo3BrY0TWiXeXVFLLcimb2jYgGYPCrEQJBANBa\nsFdRUwvnWbuAA80obVsCT06W93IPmDD69MrSVHs34OtUF4n0bqBGJax/ABLeHepi\nnOIQvxW01cIxxe3WzfMCQQCQWZGu78Oov+SeI2a64PukYmZXkvI85UdSMKvT4Ey/\nHASBA/VPYQlhScznIMKHNwXpIqYqInjh/1QvHZ/0h0jf\n-----END RSA PRIVATE KEY-----"
|
||||
|
||||
#Config PASSPORT
|
||||
PASSPORT_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA1IW8ZeL+cwbatI1sQwt2zEmWwI2ovityTTz3/O+WGXgD85Zz\nEOA0thy91mJMNZv5qyWPexbmROrYpUSe9mQl4HIDlMipuWE+pJImmrJGGCf15QdO\nOVQvoknwVxr3lfSGwEFx2ubPMb1asytawbzQ/pZc6F7VP8gqcdVpI0JnolDtXa/v\niaURTIvYY1WtwPjRa4m98fin4aKMh3sDt88W00RaMjPn00aW8NRo8s/Oa0d/DXEI\ne08RGGUBHuuqRhzB4wHYnpafBqpZDp2LYHvdw+7Vf4dPh63jfBy6ISv+eGSIFuSE\npuiumDt4J7ZjCjh+RDavJQhfGGiG+kzMZ4iAZwIDAQABAoIBACME0nF7gPAVTg54\nS0GU7wNkkNmzvf1wDUqa5EYieHpD42rM/LLoLudfPwzHb8VZqT9BVi4zLMhoZkB9\nWTBCeldMkjh/BDCOzJKznnbZL2GlnAgcNxCNRbgZNOg1glyMSXP+lLM8WyHYEMz7\nNN49rbZ1smN71OnIou3U+5kaxRbir8RNh93fp5yt519a7gRybL8Td2FH64lcSRuX\nHVDtwX95d9m8tY8WoxQPz7jzztUlfNWgRgQhBSYXpOjAEWoJaXnOYo2mxoR6pm9p\npqgkgGvwmfv0Mi97anFoPMymM3HzUFOqqtr5Q7M6DXC+1CSmtkw6hvpED/IV6RJh\nOQtG6hECgYEA/fdnE6m7NMJe4jZxq+mB7+4HYvHLodl8Vb0ncIHwbhAiqaoQNUj2\nfzotHdBeligiives4S3N10RwvKNb1M0iJs41GmfTLcJRoUvyfHbYWLX+M5FRdQ4q\nvihFj8ckontcdXUSoqdZXz0KcVMkHq1hnXt7CayfvXwTeFDdfPoevUkCgYEA1jlg\n6pYg3xGAGNPF5FGiVEMp+BT7h6w41fRmL7c7LFkksUkXmbOIY+M/NLzx2mNUUXvL\nOfMjFUtjr2kehApS6/v7pgJjqqcmFYQJAMnwsVmuBVDw7+OCxK7IrR24jwYLpVMd\nzOiWALZMlLD1bnP0v6sa0hb5/ag8bFElpV+FwC8CgYEAromI3YqYjfnHG9Au7ubb\n1fjQOr/SIrlFKeeFY1zpz7pnGBM4cGZkgauJtiOt3aRXmQn+VgMUpAz1La9XPTh9\ncA3nkO4pxBj34NJBJCjJJq5stSP5x2ilF2q148oI82G0eUSsOfyo/zsEIj3xZOPj\nYkeql0t7vM2408c/cNS0q4ECgYEArDX8HxkI28npvAuiLeUiJbLIblIP0gU0u2p5\nKyqVOxV+VbZ4bmrQ3du01+R8WB85jTeDK9a1AU1VmZFborHZ7zLmHZIWJP2xs+Is\niqHMCAYbytJCndW7LfmEAQa/ctpdSk4CytK+o1vpPC71XhGBUwNt0C4AUVWJHVou\ndT7Q+qkCgYAE0QGNls/EUcCFoX6LUXDAQZFe46rp5hxcGOrjdjbgZl5DiJSrnEvH\n1sh908Q1FchJagA+nUVOm+nbOV3EMf6XlHRyB9XtRcSgEfls9O0HWUi/67YJig9L\ncElLxwyrZpLdzMRYz0JknXSb7GnnsZPG4HG5rhMMz/Ly7lb6f7GZ1w==\n-----END RSA PRIVATE KEY-----"
|
||||
PASSPORT_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1IW8ZeL+cwbatI1sQwt2\nzEmWwI2ovityTTz3/O+WGXgD85ZzEOA0thy91mJMNZv5qyWPexbmROrYpUSe9mQl\n4HIDlMipuWE+pJImmrJGGCf15QdOOVQvoknwVxr3lfSGwEFx2ubPMb1asytawbzQ\n/pZc6F7VP8gqcdVpI0JnolDtXa/viaURTIvYY1WtwPjRa4m98fin4aKMh3sDt88W\n00RaMjPn00aW8NRo8s/Oa0d/DXEIe08RGGUBHuuqRhzB4wHYnpafBqpZDp2LYHvd\nw+7Vf4dPh63jfBy6ISv+eGSIFuSEpuiumDt4J7ZjCjh+RDavJQhfGGiG+kzMZ4iA\nZwIDAQAB\n-----END PUBLIC KEY-----"
|
||||
RSA_KEY=
|
||||
RSA_PUBLIC=
|
||||
RSA_PRIVATE=
|
||||
RSA_PREVIOUS_KEY=
|
||||
RSA_PREVIOUS_PUBLIC=
|
||||
|
||||
#Config VMware template default credential
|
||||
VMWARE_TEMPLATE_PASSWORD=change-me
|
||||
VMWARE_TEMPLATE_PASSWORD=
|
||||
|
||||
#Config vCenter/ESXi TLS + jump host SSH verification (see config/vmware.php)
|
||||
VCENTER_TLS_VERIFY=true
|
||||
VCENTER_CA_BUNDLE=
|
||||
VCENTER_SSH_KNOWN_HOSTS=
|
||||
|
||||
#Config Plesk API TLS verification (see config/services.php)
|
||||
PLESK_TLS_VERIFY=true
|
||||
PLESK_CA_BUNDLE=
|
||||
|
||||
#CONFIG CKFINDER
|
||||
CKFINDER_DOMAIN=client.test
|
||||
CKFINDER_LICENSE=WS8SXEQQXPN8MYTF51SX1VFFUW3B6
|
||||
|
||||
PASSPORT_PERSONAL_ACCESS_CLIENT_ID=9c1e5bea-4c4e-4c86-8a29-91e7444d3897
|
||||
PASSPORT_PERSONAL_ACCESS_CLIENT_SECRET=T3TGImDGDT0p2I9wD4ckunLZV9iHyJbl378s83HQ
|
||||
CKFINDER_LICENSE=
|
||||
|
||||
BROADCAST_DRIVER=pusher
|
||||
CACHE_DRIVER=redis
|
||||
@@ -46,18 +50,18 @@ SESSION_LIFETIME=240
|
||||
MEMCACHED_HOST=127.0.0.1
|
||||
|
||||
REDIS_HOST=127.0.0.1
|
||||
REDIS_PASSWORD=Redis@9999
|
||||
REDIS_PASSWORD=
|
||||
REDIS_PORT=6379
|
||||
REDIS_CLIENT=predis
|
||||
|
||||
TELEGRAM_BOT_ID=6972012759
|
||||
TELEGRAM_BOT_TOKEN=8022195470:AAFU_cv79UAzSWvPW_tiYA21dCD9oNnTRus
|
||||
TELEGRAM_BOT_ID=
|
||||
TELEGRAM_BOT_TOKEN=
|
||||
|
||||
MAIL_MAILER=smtp
|
||||
MAIL_HOST=smtp.gmail.com
|
||||
MAIL_PORT=465
|
||||
MAIL_USERNAME=pbao.business@gmail.com
|
||||
MAIL_PASSWORD=uusxfksjtcorivqh
|
||||
MAIL_USERNAME=
|
||||
MAIL_PASSWORD=
|
||||
MAIL_ENCRYPTION=tls
|
||||
MAIL_FROM_ADDRESS=noreply@yourdomain.com
|
||||
|
||||
@@ -67,16 +71,16 @@ AWS_DEFAULT_REGION=us-east-1
|
||||
AWS_BUCKET=
|
||||
AWS_USE_PATH_STYLE_ENDPOINT=false
|
||||
|
||||
PUSHER_APP_ID=2158258
|
||||
PUSHER_APP_KEY=08113c904934c0bc7581
|
||||
PUSHER_APP_SECRET=8402ee6ff613513a1dad
|
||||
PUSHER_APP_ID=
|
||||
PUSHER_APP_KEY=
|
||||
PUSHER_APP_SECRET=
|
||||
PUSHER_APP_CLUSTER=ap1
|
||||
|
||||
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
|
||||
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
|
||||
|
||||
VNPAY_TMN_CODE=BU4VVGV5
|
||||
VNPAY_HASH_SECRET=ISDSSDEGJ8EKDHXJVTVMD919DAFBF96I
|
||||
VNPAY_TMN_CODE=
|
||||
VNPAY_HASH_SECRET=
|
||||
VNPAY_URL=https://sandbox.vnpayment.vn/paymentv2/vpcpay.html
|
||||
VNPAY_RETURN_URL=https://api-agency.test/v1/transaction/return
|
||||
VNPAY_API_URL=http://sandbox.vnpayment.vn/merchant_webapi/merchant.html
|
||||
@@ -85,8 +89,6 @@ FRONTEND_URL=https://portal.test
|
||||
|
||||
# openssl rand -hex 32
|
||||
CLIENT_API_ACCESS_KEY=
|
||||
CLIENT_API_ACCESS_SECRET="tgs-client-api"
|
||||
|
||||
|
||||
CLIENT_API_ACCESS_SECRET=
|
||||
|
||||
WMKS_HOST=10.10.10.120
|
||||
@@ -12,11 +12,12 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Deploy
|
||||
uses: appleboy/ssh-action@v1.2.0
|
||||
uses: appleboy/ssh-action@7eaf76671a0d7eec5d98ee897acda4f968735a17 # v1.2.0
|
||||
with:
|
||||
host: ${{ secrets.HOST }}
|
||||
username: ${{ secrets.USERNAME }}
|
||||
password: ${{ secrets.PASSWORD }}
|
||||
key: ${{ secrets.SSH_PRIVATE_KEY }}
|
||||
fingerprint: ${{ secrets.SSH_HOST_FINGERPRINT }}
|
||||
port: ${{ secrets.PORT }}
|
||||
script_stop: true
|
||||
script: |
|
||||
@@ -58,9 +59,9 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
composer install
|
||||
composer install --no-dev --optimize-autoloader
|
||||
|
||||
composer dump-autoload
|
||||
composer dump-autoload --no-dev --optimize
|
||||
|
||||
php artisan migrate --force
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
name: Secret scan
|
||||
|
||||
on:
|
||||
push:
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
gitleaks:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Scan new commits
|
||||
env:
|
||||
RANGE: ${{ github.event_name == 'pull_request' && format('{0}..{1}', github.event.pull_request.base.sha, github.event.pull_request.head.sha) || format('{0}..{1}', github.event.before, github.sha) }}
|
||||
run: |
|
||||
case "$RANGE" in 0000000000000000000000000000000000000000..*) RANGE="${GITHUB_SHA}~1..${GITHUB_SHA}" ;; esac
|
||||
curl -sSfL https://github.com/gitleaks/gitleaks/releases/download/v8.30.1/gitleaks_8.30.1_linux_x64.tar.gz | tar xz gitleaks
|
||||
./gitleaks git --redact --no-banner --log-opts="$RANGE" .
|
||||
File diff suppressed because one or more lines are too long
@@ -40,7 +40,7 @@ class HostingMail extends Command
|
||||
|
||||
if ($Hosting)
|
||||
{
|
||||
$ServiceExpiry = Carbon::now()->diffInDays(Carbon::parse($Hosting->next_due_date),false);
|
||||
$ServiceExpiry = (int) Carbon::now()->diffInDays(Carbon::parse($Hosting->next_due_date), false);
|
||||
if ($ServiceExpiry <= 5 && $ServiceExpiry >= 0)
|
||||
{
|
||||
$jobs[] = new ExpiryMail($item->id,5,3);
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Http\Facade\SignRSA;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
class ReencryptSecrets extends Command
|
||||
{
|
||||
protected $signature = 'secrets:reencrypt {--dry-run}';
|
||||
|
||||
protected $description = 'Re-encrypt stored secrets with the current APP_KEY and RSA_KEY (old values are read via APP_PREVIOUS_KEYS / RSA_PREVIOUS_*)';
|
||||
|
||||
private const RSA_COLUMNS = [
|
||||
['module_vcenter', 'password'],
|
||||
['infra_management', 'password'],
|
||||
['module_hosting', 'password'],
|
||||
['module_hosting_server', 'password'],
|
||||
['module_dns_server', 'password'],
|
||||
['module_vmware', 'password'],
|
||||
['reinstall_logs', 'password'],
|
||||
];
|
||||
|
||||
private const APP_KEY_COLUMNS = [
|
||||
['dns_manager_servers', 'password'],
|
||||
['module_hosting_plesk_clients', 'password'],
|
||||
['module_vmware', 'plain_password'],
|
||||
['reinstall_logs', 'plain_password'],
|
||||
];
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$failed = 0;
|
||||
|
||||
foreach (self::RSA_COLUMNS as [$table, $column]) {
|
||||
$failed += $this->reencryptColumn($table, $column, fn (string $value) => SignRSA::EncryptFunc($this->decryptRsa($value)));
|
||||
}
|
||||
|
||||
foreach (self::APP_KEY_COLUMNS as [$table, $column]) {
|
||||
$failed += $this->reencryptColumn($table, $column, fn (string $value) => Crypt::encryptString(Crypt::decryptString($value)));
|
||||
}
|
||||
|
||||
$failed += $this->reencryptSmtpSetting();
|
||||
|
||||
return $failed === 0 ? self::SUCCESS : self::FAILURE;
|
||||
}
|
||||
|
||||
private function reencryptColumn(string $table, string $column, callable $reencrypt): int
|
||||
{
|
||||
if (!Schema::hasColumn($table, $column)) {
|
||||
$this->warn("{$table}.{$column}: column not found, skipped");
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
$updated = 0;
|
||||
$failed = 0;
|
||||
|
||||
DB::table($table)
|
||||
->select(['id', $column])
|
||||
->whereNotNull($column)
|
||||
->where($column, '!=', '')
|
||||
->chunkById(200, function ($rows) use ($table, $column, $reencrypt, &$updated, &$failed) {
|
||||
foreach ($rows as $row) {
|
||||
try {
|
||||
$value = $reencrypt((string) $row->{$column});
|
||||
} catch (Throwable) {
|
||||
$failed++;
|
||||
$this->warn("{$table}#{$row->id}.{$column}: cannot decrypt with current or previous key");
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!$this->option('dry-run')) {
|
||||
DB::table($table)->where('id', $row->id)->update([$column => $value]);
|
||||
}
|
||||
$updated++;
|
||||
}
|
||||
});
|
||||
|
||||
$this->info("{$table}.{$column}: {$updated} re-encrypted, {$failed} failed");
|
||||
|
||||
return $failed;
|
||||
}
|
||||
|
||||
private function reencryptSmtpSetting(): int
|
||||
{
|
||||
$setting = DB::table('setting')->where('key', 'smtp')->first();
|
||||
$smtp = $setting ? json_decode((string) $setting->value, true) : null;
|
||||
|
||||
if (empty($smtp['password'])) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
try {
|
||||
$smtp['password'] = SignRSA::EncryptFunc($this->decryptRsa($smtp['password']));
|
||||
} catch (Throwable) {
|
||||
$this->warn('setting[smtp].password: cannot decrypt with current or previous key');
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!$this->option('dry-run')) {
|
||||
DB::table('setting')->where('key', 'smtp')->update(['value' => json_encode($smtp)]);
|
||||
}
|
||||
$this->info('setting[smtp].password: re-encrypted');
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private function decryptRsa(string $value): string
|
||||
{
|
||||
$plain = SignRSA::DecryptFunc($value);
|
||||
if ($plain === '') {
|
||||
throw new RuntimeException('RSA decrypt failed');
|
||||
}
|
||||
|
||||
return $plain;
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ use App\Repositories\Api\Service\ServiceRepository;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\InvoiceItem;
|
||||
use App\Models\Service;
|
||||
use App\Support\RenewalPricing;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
@@ -230,8 +231,10 @@ class ServiceExpiry extends Command
|
||||
return;
|
||||
}
|
||||
|
||||
$price = $this->renewalPrice($orderItem);
|
||||
$renewalPrice = $this->renewalPrice($orderItem);
|
||||
$months = $orderItem->months ?? 1;
|
||||
$addonTotal = RenewalPricing::addonTotal($service, 1);
|
||||
$price = $renewalPrice + $addonTotal;
|
||||
|
||||
if ($price <= 0) {
|
||||
Log::warning('service:expiry | Cannot create renewal invoice: zero price', ['service_id' => $service->id]);
|
||||
@@ -270,12 +273,16 @@ class ServiceExpiry extends Command
|
||||
'product_id' => $service->product_id,
|
||||
'type' => 'renewal',
|
||||
'description' => 'Gia hạn dịch vụ: ' . ($orderItem->product?->name ?? $service->server_name ?? ''),
|
||||
'months' => $orderItem->months ?? 1,
|
||||
'months' => $months,
|
||||
'quantity' => 1,
|
||||
'unit_price' => $price,
|
||||
'total_price' => $price,
|
||||
'unit_price' => $renewalPrice,
|
||||
'total_price' => $renewalPrice,
|
||||
]);
|
||||
|
||||
foreach (RenewalPricing::addonInvoiceItems($service, 1, $months) as $addonItem) {
|
||||
InvoiceItem::create($addonItem + ['invoice_id' => $invoice->id]);
|
||||
}
|
||||
|
||||
// Update service to point to the new renewal invoice
|
||||
$service->update(['invoice_id' => $invoice->id]);
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ class ServiceHosting extends Command
|
||||
$Hosting = ModuleHosting::with('Server')->where('customer_id',$item->id)->first();
|
||||
if ($Hosting)
|
||||
{
|
||||
$ServiceExpiry = Carbon::now()->diffInDays(Carbon::parse($Hosting->next_due_date),false);
|
||||
$ServiceExpiry = (int) Carbon::now()->diffInDays(Carbon::parse($Hosting->next_due_date), false);
|
||||
if ($ServiceExpiry <= 0)
|
||||
{
|
||||
$jobs[] = new HostingJobs($item->id,'Suspend');
|
||||
|
||||
@@ -42,7 +42,7 @@ class ServiceVPS extends Command
|
||||
{
|
||||
foreach ($allService as $service)
|
||||
{
|
||||
$ServiceExpiry = Carbon::now()->diffInDays(Carbon::parse($service->next_due_date),false);
|
||||
$ServiceExpiry = (int) Carbon::now()->diffInDays(Carbon::parse($service->next_due_date), false);
|
||||
|
||||
if ($ServiceExpiry <= 0)
|
||||
{
|
||||
|
||||
@@ -39,7 +39,7 @@ class VPSMail extends Command
|
||||
$vps = ModuleVmware::where('customer_id',$item->id)->first();
|
||||
if ($vps)
|
||||
{
|
||||
$ServiceExpiry = Carbon::now()->diffInDays(Carbon::parse($vps->next_due_date),false);
|
||||
$ServiceExpiry = (int) Carbon::now()->diffInDays(Carbon::parse($vps->next_due_date), false);
|
||||
if ($ServiceExpiry <= 5 && $ServiceExpiry > 0)
|
||||
{
|
||||
$jobs[] = new ExpiryMail($vps->id,5,4);
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Whmcs;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class SyncAllCommand extends Command
|
||||
{
|
||||
protected $signature = 'whmcs:sync-all {--with-domain-sync : Also run domain:sync before whmcs:sync-domains}';
|
||||
|
||||
protected $description = 'Run every whmcs:sync-* command in dependency order (clients, products, orders, order-items, invoices, services, domains)';
|
||||
|
||||
private const STEPS = [
|
||||
['command' => 'whmcs:sync-clients', 'forceSync' => true],
|
||||
['command' => 'whmcs:sync-products', 'forceSync' => false],
|
||||
['command' => 'whmcs:sync-orders', 'forceSync' => true],
|
||||
['command' => 'whmcs:sync-order-items', 'forceSync' => false],
|
||||
['command' => 'whmcs:sync-invoices', 'forceSync' => true],
|
||||
['command' => 'whmcs:sync-services', 'forceSync' => false],
|
||||
['command' => 'whmcs:sync-domains', 'forceSync' => false],
|
||||
];
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
if ($this->option('with-domain-sync')) {
|
||||
$exitCode = $this->runStep('domain:sync', []);
|
||||
if ($exitCode !== self::SUCCESS) {
|
||||
return $exitCode;
|
||||
}
|
||||
} else {
|
||||
$this->warn('Skipping domain:sync — whmcs:sync-domains expects it to already be up to date. Pass --with-domain-sync to run it here.');
|
||||
}
|
||||
|
||||
foreach (self::STEPS as $step) {
|
||||
$arguments = $step['forceSync'] ? ['--sync' => true] : [];
|
||||
$exitCode = $this->runStep($step['command'], $arguments);
|
||||
|
||||
if ($exitCode !== self::SUCCESS) {
|
||||
return $exitCode;
|
||||
}
|
||||
}
|
||||
|
||||
$this->info('whmcs:sync-all completed successfully.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private function runStep(string $command, array $arguments): int
|
||||
{
|
||||
$this->newLine();
|
||||
$this->info("==> {$command}");
|
||||
|
||||
$exitCode = $this->call($command, $arguments);
|
||||
|
||||
if ($exitCode !== self::SUCCESS) {
|
||||
$this->error("{$command} failed with exit code {$exitCode}; stopping.");
|
||||
}
|
||||
|
||||
return $exitCode;
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ enum ProductBillingCycle: string
|
||||
case ONE_TIME = 'onetime';
|
||||
case MONTHLY = 'monthly';
|
||||
case QUARTERLY = 'quarterly';
|
||||
case SEMI_ANNUALLY = 'semiannually';
|
||||
case SEMI_ANNUALLY = 'semi_annually';
|
||||
case ANNUALLY = 'annually';
|
||||
case BIENNIALLY = 'biennially';
|
||||
case TRIENNIALLY = 'triennially';
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Helpers;
|
||||
|
||||
use App\Enums\Product\ProductBillingCycle;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\Order;
|
||||
use Illuminate\Support\Str;
|
||||
@@ -31,17 +32,14 @@ class OrderHelper
|
||||
return $number;
|
||||
}
|
||||
|
||||
/** Number of months a billing_cycle value represents (used for pricing and expires_at math). */
|
||||
/**
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public static function cycleToMonths(?string $cycle): int
|
||||
{
|
||||
return match ($cycle) {
|
||||
'monthly' => 1,
|
||||
'quarterly' => 3,
|
||||
'semi_annually' => 6,
|
||||
'annually' => 12,
|
||||
'biennially' => 24,
|
||||
'triennially' => 36,
|
||||
default => 1,
|
||||
};
|
||||
$enum = ProductBillingCycle::tryFrom($cycle ?? '')
|
||||
?? throw new \InvalidArgumentException("Unknown billing cycle: " . ($cycle ?? 'null'));
|
||||
|
||||
return $enum === ProductBillingCycle::ONE_TIME ? 1 : $enum->months();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,11 +9,15 @@ use App\Services\ActivityLogger;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Tymon\JWTAuth\Facades\JWTAuth;
|
||||
use Tymon\JWTAuth\Exceptions\JWTException;
|
||||
|
||||
class AuthController extends Controller
|
||||
{
|
||||
private const LOGIN_MAX_ATTEMPTS = 5;
|
||||
private const LOGIN_DECAY_SECONDS = 60;
|
||||
|
||||
public function __construct(private readonly ActivityLogger $activityLogger) {}
|
||||
|
||||
public function login(Request $request): JsonResponse
|
||||
@@ -23,9 +27,20 @@ class AuthController extends Controller
|
||||
'password' => 'required|string',
|
||||
]);
|
||||
|
||||
$throttleKey = 'admin-login:' . strtolower($request->string('username')->toString()) . '|' . $request->ip();
|
||||
|
||||
if (RateLimiter::tooManyAttempts($throttleKey, self::LOGIN_MAX_ATTEMPTS)) {
|
||||
return response()->json([
|
||||
'error' => true,
|
||||
'message' => 'Bạn đã đăng nhập sai quá nhiều lần. Vui lòng thử lại sau ít phút.',
|
||||
], 429);
|
||||
}
|
||||
|
||||
$token = Auth::guard('admin')->attempt($request->only('username', 'password'));
|
||||
|
||||
if (!$token) {
|
||||
RateLimiter::hit($throttleKey, self::LOGIN_DECAY_SECONDS);
|
||||
|
||||
$this->activityLogger->log(
|
||||
event: 'login_failed',
|
||||
logName: 'auth',
|
||||
@@ -37,6 +52,8 @@ class AuthController extends Controller
|
||||
], 401);
|
||||
}
|
||||
|
||||
RateLimiter::clear($throttleKey);
|
||||
|
||||
$user = Auth::guard('admin')->user();
|
||||
|
||||
$this->activityLogger->logAuth('login', 'admin', $user->id, $user->username ?? $user->email);
|
||||
|
||||
@@ -362,6 +362,8 @@ class CustomerController extends Controller
|
||||
'started_at' => 'nullable|date',
|
||||
'expires_at' => 'nullable|date',
|
||||
'note' => 'nullable|string',
|
||||
'requirements' => 'nullable|string',
|
||||
'feedback' => 'nullable|string',
|
||||
'price' => 'nullable|numeric|min:0',
|
||||
'os_id' => 'nullable|integer|exists:os,id',
|
||||
'vm_cpu' => 'nullable|integer|min:1',
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\Admin\DnsManager;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Registrar;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class RegistrarController extends Controller
|
||||
{
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'data' => Registrar::where('status', 'active')->orderBy('name')->get(['id', 'name', 'short_name', 'website']),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -92,6 +92,11 @@ class EmployeeController extends Controller
|
||||
|
||||
$request->validated();
|
||||
|
||||
$guardError = $this->guardEmployeeMutation($employee, $request->role);
|
||||
if ($guardError) {
|
||||
return $guardError;
|
||||
}
|
||||
|
||||
try {
|
||||
DB::beginTransaction();
|
||||
|
||||
@@ -138,6 +143,14 @@ class EmployeeController extends Controller
|
||||
], 404);
|
||||
}
|
||||
|
||||
$currentUser = auth('admin')->user();
|
||||
if ($employee->hasRole('Full Administrator') && !$currentUser->hasRole('Full Administrator')) {
|
||||
return response()->json([
|
||||
'error' => true,
|
||||
'message' => 'Bạn không có quyền xoá tài khoản Full Administrator.',
|
||||
], 403);
|
||||
}
|
||||
|
||||
try {
|
||||
DB::beginTransaction();
|
||||
$this->employeeRepository->delete($id);
|
||||
@@ -156,6 +169,34 @@ class EmployeeController extends Controller
|
||||
}
|
||||
}
|
||||
|
||||
private function guardEmployeeMutation($employee, string $requestedRole): ?JsonResponse
|
||||
{
|
||||
$currentUser = auth('admin')->user();
|
||||
|
||||
if ($employee->hasRole('Full Administrator') && !$currentUser->hasRole('Full Administrator')) {
|
||||
return response()->json([
|
||||
'error' => true,
|
||||
'message' => 'Bạn không có quyền sửa tài khoản Full Administrator.',
|
||||
], 403);
|
||||
}
|
||||
|
||||
if ($employee->id === $currentUser->id && !$currentUser->hasRole($requestedRole)) {
|
||||
return response()->json([
|
||||
'error' => true,
|
||||
'message' => 'Bạn không thể tự đổi vai trò của chính mình.',
|
||||
], 403);
|
||||
}
|
||||
|
||||
if (in_array($requestedRole, ['Administrator', 'Full Administrator'], true) && !$currentUser->hasRole('Full Administrator')) {
|
||||
return response()->json([
|
||||
'error' => true,
|
||||
'message' => 'Chỉ Full Administrator mới có quyền gán vai trò này.',
|
||||
], 403);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function roles(): JsonResponse
|
||||
{
|
||||
$roles = Role::where('guard_name', 'admin')->get(['id', 'name']);
|
||||
|
||||
@@ -194,13 +194,13 @@ class ProductController extends Controller
|
||||
{
|
||||
$currency = $data['currency'] ?? 'VND';
|
||||
$cycles = [
|
||||
'monthly' => 'price_monthly',
|
||||
'quarterly' => 'price_quarterly',
|
||||
'semiannually' => 'price_semiannually',
|
||||
'annually' => 'price_annually',
|
||||
'biennially' => 'price_biennially',
|
||||
'triennially' => 'price_triennially',
|
||||
'onetime' => 'price_onetime',
|
||||
'monthly' => 'price_monthly',
|
||||
'quarterly' => 'price_quarterly',
|
||||
'semi_annually' => 'price_semiannually',
|
||||
'annually' => 'price_annually',
|
||||
'biennially' => 'price_biennially',
|
||||
'triennially' => 'price_triennially',
|
||||
'onetime' => 'price_onetime',
|
||||
];
|
||||
|
||||
foreach ($cycles as $cycle => $field) {
|
||||
|
||||
@@ -36,7 +36,7 @@ class ServiceController extends Controller
|
||||
|
||||
public function show(int $id): JsonResponse
|
||||
{
|
||||
$service = Service::with(['customer', 'product', 'orderItem', 'invoice', 'vmware.os.osGroup', 'addons'])
|
||||
$service = Service::with(['customer', 'product', 'orderItem', 'invoice', 'vmware.os.osGroup', 'addons', ...Service::HOSTING_ACCOUNT_RELATIONS])
|
||||
->findOrFail($id);
|
||||
|
||||
ModuleVmware::resolveVirtualMachineIds([$service->vmware]);
|
||||
|
||||
@@ -186,7 +186,7 @@ class SettingController extends Controller
|
||||
public function uploadMedia(Request $request): JsonResponse
|
||||
{
|
||||
$request->validate([
|
||||
'file' => 'required|file|mimes:jpg,jpeg,png,webp,svg|max:5120',
|
||||
'file' => 'required|file|mimes:jpg,jpeg,png,webp|max:5120',
|
||||
]);
|
||||
|
||||
$path = $request->file('file')->store('system-config', 'public');
|
||||
|
||||
@@ -64,7 +64,7 @@ class AdminTransactionController extends Controller
|
||||
'type' => $t->type,
|
||||
'status' => $t->status,
|
||||
'status_label' => TransactionStatus::from((int) $t->status)->label(),
|
||||
'proof_image' => $t->proof_image ? Storage::disk('public')->url($t->proof_image) : null,
|
||||
'proof_image' => $t->proof_image_urls[0] ?? null,
|
||||
'created_at' => $t->created_at?->toISOString(),
|
||||
'customer' => $t->customer ? [
|
||||
'uuid' => $t->customer->uuid,
|
||||
@@ -287,4 +287,21 @@ class AdminTransactionController extends Controller
|
||||
'message' => 'Đã từ chối giao dịch',
|
||||
]);
|
||||
}
|
||||
|
||||
public function proofImage(Transaction $transaction, int $index = 0)
|
||||
{
|
||||
abort_unless($transaction->proof_image, 404);
|
||||
|
||||
$paths = json_decode((string) $transaction->proof_image, true);
|
||||
$paths = is_array($paths) ? array_values($paths) : [$transaction->proof_image];
|
||||
$path = $paths[$index] ?? null;
|
||||
|
||||
abort_unless(is_string($path) && $path !== '', 404);
|
||||
|
||||
$disk = Storage::disk('local')->exists($path) ? 'local' : 'public';
|
||||
|
||||
abort_unless(Storage::disk($disk)->exists($path), 404);
|
||||
|
||||
return Storage::disk($disk)->response($path, null, ['Cache-Control' => 'private, no-store']);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ use App\Services\ActivityLogger;
|
||||
use App\Services\Api\Client\ClientAuthService;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Validation\Rules\Password;
|
||||
|
||||
/**
|
||||
* @OA\Tag(
|
||||
@@ -411,7 +412,7 @@ class ClientController extends Controller
|
||||
$data = $request->validate([
|
||||
'email' => ['required', 'email', 'max:255'],
|
||||
'token' => ['required', 'string', 'max:255'],
|
||||
'password' => ['required', 'string', 'min:8', 'confirmed'],
|
||||
'password' => ['required', Password::min(10), 'confirmed'],
|
||||
]);
|
||||
|
||||
$customer = $this->authService->resetPassword($data);
|
||||
@@ -439,7 +440,17 @@ class ClientController extends Controller
|
||||
|
||||
abort_unless($path && str_starts_with($path, 'cccd/') && Storage::disk('local')->exists($path), 404);
|
||||
|
||||
return Storage::disk('local')->response($path, null, ['Cache-Control' => 'private, no-store']);
|
||||
$mime = match (strtolower(pathinfo($path, PATHINFO_EXTENSION))) {
|
||||
'png' => 'image/png',
|
||||
'webp' => 'image/webp',
|
||||
default => 'image/jpeg',
|
||||
};
|
||||
|
||||
return Storage::disk('local')->response($path, "cccd-{$side}", [
|
||||
'Content-Type' => $mime,
|
||||
'Content-Disposition' => "inline; filename=\"cccd-{$side}\"",
|
||||
'Cache-Control' => 'private, no-store',
|
||||
]);
|
||||
}
|
||||
|
||||
public function update(ClientUpdateRequest $request)
|
||||
|
||||
@@ -112,7 +112,9 @@ class DomainController extends Controller
|
||||
} catch (\Throwable $e) {
|
||||
DB::rollBack();
|
||||
|
||||
return response()->json(['error' => true, 'message' => $e->getMessage()], 500);
|
||||
\Log::error('DomainController::storeRecord error: ' . $e->getMessage());
|
||||
|
||||
return response()->json(['error' => true, 'message' => 'Có lỗi xảy ra, vui lòng thử lại'], 500);
|
||||
}
|
||||
|
||||
$customer = $request->user();
|
||||
|
||||
@@ -9,7 +9,7 @@ use Illuminate\Http\Request;
|
||||
|
||||
trait ResolvesVm
|
||||
{
|
||||
protected function resolveVmById(int|string $productId, Request $request): ModuleVmware|JsonResponse
|
||||
protected function resolveVmById(int|string $productId, Request $request, bool $requireActiveService = true): ModuleVmware|JsonResponse
|
||||
{
|
||||
$customer = $request->user();
|
||||
$vm = null;
|
||||
@@ -42,6 +42,13 @@ trait ResolvesVm
|
||||
return response()->json(['error' => true, 'message' => 'Bạn không có quyền thao tác VM này'], 403);
|
||||
}
|
||||
|
||||
if ($requireActiveService) {
|
||||
$service = $vm->service ?? Service::where('vm_id', $vm->vmware_id)->first();
|
||||
if ($service && $service->status !== 'active') {
|
||||
return response()->json(['error' => true, 'message' => 'Dịch vụ không ở trạng thái hoạt động, không thể thao tác.'], 403);
|
||||
}
|
||||
}
|
||||
|
||||
return $vm;
|
||||
}
|
||||
|
||||
|
||||
@@ -105,8 +105,16 @@ class OrderControllerRefactor extends Controller
|
||||
],
|
||||
201,
|
||||
);
|
||||
} catch (\Throwable $e) {
|
||||
} catch (\Illuminate\Validation\ValidationException $e) {
|
||||
return response()->json(
|
||||
['success' => false, 'message' => collect($e->errors())->flatten()->first() ?? $e->getMessage()],
|
||||
422,
|
||||
);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return response()->json(['success' => false, 'message' => $e->getMessage()], 400);
|
||||
} catch (\Throwable $e) {
|
||||
\Log::error('OrderControllerRefactor::storeOrder error: ' . $e->getMessage());
|
||||
return response()->json(['success' => false, 'message' => 'Có lỗi xảy ra, vui lòng thử lại'], 500);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,10 +128,11 @@ class OrderControllerRefactor extends Controller
|
||||
|
||||
try {
|
||||
$this->orderService->pay($order, $request->payment_method);
|
||||
} catch (\Throwable $e) {
|
||||
// Số dư không đủ / đơn đã thanh toán là lỗi nghiệp vụ, không phải lỗi server —
|
||||
// trả 422 cho khớp với payClientInvoiceByNumber.
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return response()->json(['success' => false, 'message' => $e->getMessage()], 422);
|
||||
} catch (\Throwable $e) {
|
||||
\Log::error('OrderControllerRefactor::payOrder error: ' . $e->getMessage());
|
||||
return response()->json(['success' => false, 'message' => 'Có lỗi xảy ra, vui lòng thử lại'], 500);
|
||||
}
|
||||
|
||||
$this->activityLogger->log(
|
||||
@@ -250,8 +259,11 @@ class OrderControllerRefactor extends Controller
|
||||
: 'Thanh toán hóa đơn thành công.',
|
||||
'data' => new InvoiceDetailResource($paidInvoice),
|
||||
]);
|
||||
} catch (\Throwable $e) {
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return response()->json(['success' => false, 'message' => $e->getMessage()], 422);
|
||||
} catch (\Throwable $e) {
|
||||
\Log::error('OrderControllerRefactor::payClientInvoiceByNumber error: ' . $e->getMessage());
|
||||
return response()->json(['success' => false, 'message' => 'Có lỗi xảy ra, vui lòng thử lại'], 500);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -286,33 +286,33 @@ class ProductCategoryController extends Controller
|
||||
private function formatProduct($product): array
|
||||
{
|
||||
$billingCycleLabels = [
|
||||
'monthly' => 'Hàng tháng',
|
||||
'quarterly' => 'Hàng quý',
|
||||
'semiannually' => 'Nửa năm',
|
||||
'annually' => 'Hàng năm',
|
||||
'biennially' => '2 năm',
|
||||
'triennially' => '3 năm',
|
||||
'onetime' => 'Một lần',
|
||||
'monthly' => 'Hàng tháng',
|
||||
'quarterly' => 'Hàng quý',
|
||||
'semi_annually' => 'Nửa năm',
|
||||
'annually' => 'Hàng năm',
|
||||
'biennially' => '2 năm',
|
||||
'triennially' => '3 năm',
|
||||
'onetime' => 'Một lần',
|
||||
];
|
||||
|
||||
$periodMonths = [
|
||||
'monthly' => 1,
|
||||
'quarterly' => 3,
|
||||
'semiannually' => 6,
|
||||
'annually' => 12,
|
||||
'biennially' => 24,
|
||||
'triennially' => 36,
|
||||
'onetime' => 0,
|
||||
'monthly' => 1,
|
||||
'quarterly' => 3,
|
||||
'semi_annually' => 6,
|
||||
'annually' => 12,
|
||||
'biennially' => 24,
|
||||
'triennially' => 36,
|
||||
'onetime' => 0,
|
||||
];
|
||||
|
||||
$periodUnits = [
|
||||
'monthly' => 'month',
|
||||
'quarterly' => 'quarter',
|
||||
'semiannually' => 'semi_year',
|
||||
'annually' => 'year',
|
||||
'biennially' => 'biennially',
|
||||
'triennially' => 'triennially',
|
||||
'onetime' => 'none',
|
||||
'monthly' => 'month',
|
||||
'quarterly' => 'quarter',
|
||||
'semi_annually' => 'semi_year',
|
||||
'annually' => 'year',
|
||||
'biennially' => 'biennially',
|
||||
'triennially' => 'triennially',
|
||||
'onetime' => 'none',
|
||||
];
|
||||
|
||||
return [
|
||||
|
||||
@@ -191,7 +191,9 @@ class ServiceController extends Controller
|
||||
|
||||
public function getDetailServiceCustomer(Request $request, $uuid)
|
||||
{
|
||||
$service = Service::where('uuid', $uuid)->first();
|
||||
$service = Service::where('uuid', $uuid)
|
||||
->where('customer_id', $request->user()->id)
|
||||
->first();
|
||||
|
||||
if (!$service) {
|
||||
return response()->json([
|
||||
|
||||
@@ -76,7 +76,7 @@ class SnapshotController extends Controller
|
||||
return response()->json(['error' => true, 'message' => 'Thiếu product id'], 422);
|
||||
}
|
||||
|
||||
$vm = $this->resolveVmById($productParam, $request);
|
||||
$vm = $this->resolveVmById($productParam, $request, requireActiveService: false);
|
||||
if ($vm instanceof JsonResponse) {
|
||||
return $vm;
|
||||
}
|
||||
|
||||
@@ -10,10 +10,12 @@ use App\Http\Controllers\Controller;
|
||||
use App\Http\Services\vCenter;
|
||||
use App\Jobs\VirtualMachine\ChangeIpVMJob;
|
||||
use App\Jobs\VirtualMachine\ChangeVmPasswordJob;
|
||||
use App\Models\IpPool;
|
||||
use App\Models\ModuleVmware;
|
||||
use App\Models\Os;
|
||||
use App\Models\Service;
|
||||
use App\Services\ActivityLogger;
|
||||
use App\Services\VirtualMachine\VmIpReservationService;
|
||||
use App\Services\VmProvisionService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -21,9 +23,7 @@ use Illuminate\Support\Facades\Cache;
|
||||
|
||||
class VmController extends Controller
|
||||
{
|
||||
use ResolvesVm {
|
||||
ResolvesVm::resolveVmById as resolveVmForClient;
|
||||
}
|
||||
use ResolvesVm;
|
||||
|
||||
public function __construct(protected ActivityLogger $activityLogger) {}
|
||||
// -------------------------------------------------------------------------
|
||||
@@ -114,43 +114,67 @@ class VmController extends Controller
|
||||
// Change IP
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* GET /v1/system/vm-ip-options
|
||||
*
|
||||
* Query: server_name string Service.server_name
|
||||
* Lists free IP pool entries in the same network as the VM's current IP.
|
||||
*/
|
||||
public function ipOptions(Request $request): JsonResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'server_name' => ['required', 'string', 'max:255'],
|
||||
]);
|
||||
|
||||
$service = $this->findOwnedServiceByServerName($validated['server_name'], $request);
|
||||
if ($service instanceof JsonResponse) {
|
||||
return $service;
|
||||
}
|
||||
|
||||
$vm = $service->orderItem?->order?->vmWare?->first();
|
||||
if (!$vm) {
|
||||
return response()->json(['success' => false, 'message' => 'Không tìm thấy VM cho dịch vụ này.'], 404);
|
||||
}
|
||||
|
||||
$networkId = $vm->ipAddress?->module_network_id;
|
||||
if (!$networkId) {
|
||||
return response()->json(['success' => false, 'message' => 'Không xác định được mạng của VM.'], 422);
|
||||
}
|
||||
|
||||
$ips = app(VmIpReservationService::class)->freeIpsInNetwork($networkId);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $ips->map(fn (IpPool $ip) => [
|
||||
'ip_address' => $ip->ip_address,
|
||||
'gateway' => $ip->gateway,
|
||||
])->values(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /v1/system/vm-change-ip
|
||||
*
|
||||
* Body:
|
||||
* server_name string Service.server_name (e.g. "xasdf.com.vnx")
|
||||
* ip_address string New IP to assign
|
||||
* gateway string (optional) Gateway — falls back to existing IP record
|
||||
* ip_address string New IP to assign — must be a free IP from the VM's network pool
|
||||
*/
|
||||
/**
|
||||
* Dispatches ChangeIpVMJob — returns immediately, runs async.
|
||||
*/
|
||||
public function changeIp(Request $request): JsonResponse
|
||||
public function changeIp(Request $request, VmIpReservationService $ipReservation): JsonResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'server_name' => ['required', 'string', 'max:255'],
|
||||
'ip_address' => ['required', 'ip'],
|
||||
'gateway' => ['nullable', 'ip'],
|
||||
'dns' => ['nullable', 'ip'],
|
||||
'guest_user' => ['required', 'string', 'max:255'],
|
||||
'guest_password' => ['required', 'string', 'max:255'],
|
||||
]);
|
||||
|
||||
$customer = $request->user();
|
||||
|
||||
// Look up Service by server_name + owner
|
||||
// VM chain: Service → orderItem → order → vmWare (same as ServiceClientDetailResource)
|
||||
$service = Service::with([
|
||||
'orderItem.order.vmWare.vCenter',
|
||||
'orderItem.order.vmWare.ipAddress.host.datacenter.vCenter',
|
||||
'orderItem.os.osGroup',
|
||||
])
|
||||
->where('server_name', $validated['server_name'])
|
||||
->where('customer_id', $customer->id)
|
||||
->first();
|
||||
|
||||
if (!$service) {
|
||||
return response()->json(['success' => false, 'message' => 'Không tìm thấy dịch vụ.'], 404);
|
||||
$service = $this->findOwnedServiceByServerName($validated['server_name'], $request);
|
||||
if ($service instanceof JsonResponse) {
|
||||
return $service;
|
||||
}
|
||||
|
||||
$vm = $service->orderItem?->order?->vmWare?->first();
|
||||
@@ -159,29 +183,47 @@ class VmController extends Controller
|
||||
return response()->json(['success' => false, 'message' => 'Không tìm thấy VM cho dịch vụ này.'], 404);
|
||||
}
|
||||
|
||||
$networkId = $vm->ipAddress?->module_network_id;
|
||||
if (!$networkId) {
|
||||
return response()->json(['success' => false, 'message' => 'Không xác định được mạng của VM.'], 422);
|
||||
}
|
||||
|
||||
$reservation = $ipReservation->reserveInNetwork($networkId, $validated['ip_address'], $service->id);
|
||||
if (!$reservation) {
|
||||
return response()->json(['success' => false, 'message' => 'IP không thuộc pool khả dụng hoặc đã được sử dụng.'], 422);
|
||||
}
|
||||
|
||||
$oldIpPoolId = IpPool::where('module_network_id', $networkId)
|
||||
->where('service_id', $service->id)
|
||||
->where('status', 'assigned')
|
||||
->where('id', '!=', $reservation['ip_pool_id'])
|
||||
->value('id');
|
||||
|
||||
// Auto-detect OS type from the service's order item OS group
|
||||
$osGroup = strtolower($service->orderItem?->os?->osGroup?->name ?? '');
|
||||
$osType = (str_contains($osGroup, 'linux') || str_contains($osGroup, 'ubuntu') || str_contains($osGroup, 'centos'))
|
||||
? 'linux'
|
||||
: 'windows';
|
||||
|
||||
$gateway = $validated['gateway'] ?? '';
|
||||
$dns = $validated['dns'] ?? '8.8.8.8';
|
||||
$dns = $validated['dns'] ?? '8.8.8.8';
|
||||
|
||||
// ponytail: don't release — lock expires after 5 min while the async job runs
|
||||
$lock = $this->acquireVmLock($vm, 300);
|
||||
if (!$lock) {
|
||||
$ipReservation->releaseByPoolId($reservation['ip_pool_id']);
|
||||
return $this->vmLocked();
|
||||
}
|
||||
|
||||
ChangeIpVMJob::dispatch(
|
||||
$vm->id,
|
||||
$validated['ip_address'],
|
||||
$gateway,
|
||||
$reservation['gateway'],
|
||||
$osType,
|
||||
$dns,
|
||||
$validated['guest_user'],
|
||||
$validated['guest_password'],
|
||||
$reservation['ip_pool_id'],
|
||||
$oldIpPoolId,
|
||||
);
|
||||
|
||||
$this->activityLogger->log(
|
||||
@@ -189,7 +231,7 @@ class VmController extends Controller
|
||||
logName: 'VM',
|
||||
description: "Customer {$request->user()->email} yêu cầu đổi IP VM: {$vm->name} → {$validated['ip_address']}",
|
||||
subject: $vm,
|
||||
newValues: ['ip_address' => $validated['ip_address'], 'gateway' => $gateway, 'os_type' => $osType],
|
||||
newValues: ['ip_address' => $validated['ip_address'], 'gateway' => $reservation['gateway'], 'os_type' => $osType],
|
||||
);
|
||||
|
||||
return response()->json([
|
||||
@@ -198,6 +240,35 @@ class VmController extends Controller
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up a Service by server_name, verify ownership and active status.
|
||||
* Returns JsonResponse on error, Service on success.
|
||||
*/
|
||||
private function findOwnedServiceByServerName(string $serverName, Request $request): Service|JsonResponse
|
||||
{
|
||||
$customer = $request->user();
|
||||
|
||||
// VM chain: Service → orderItem → order → vmWare (same as ServiceClientDetailResource)
|
||||
$service = Service::with([
|
||||
'orderItem.order.vmWare.vCenter',
|
||||
'orderItem.order.vmWare.ipAddress.host.datacenter.vCenter',
|
||||
'orderItem.os.osGroup',
|
||||
])
|
||||
->where('server_name', $serverName)
|
||||
->where('customer_id', $customer->id)
|
||||
->first();
|
||||
|
||||
if (!$service) {
|
||||
return response()->json(['success' => false, 'message' => 'Không tìm thấy dịch vụ.'], 404);
|
||||
}
|
||||
|
||||
if ($service->status !== 'active') {
|
||||
return response()->json(['success' => false, 'message' => 'Dịch vụ không ở trạng thái hoạt động, không thể thao tác.'], 403);
|
||||
}
|
||||
|
||||
return $service;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Change Port (RDP)
|
||||
// -------------------------------------------------------------------------
|
||||
@@ -319,7 +390,7 @@ class VmController extends Controller
|
||||
return response()->json(['error' => true, 'message' => 'Thiếu product id'], 422);
|
||||
}
|
||||
|
||||
$vm = $this->resolveVmForClient($productId, $request);
|
||||
$vm = $this->resolveVmById($productId, $request);
|
||||
if ($vm instanceof JsonResponse) {
|
||||
return $vm;
|
||||
}
|
||||
@@ -431,7 +502,7 @@ class VmController extends Controller
|
||||
return response()->json(['success' => false, 'message' => 'Thiếu product id.'], 422);
|
||||
}
|
||||
|
||||
$vm = $this->resolveVmById($productId, $request);
|
||||
$vm = $this->resolveVmById($productId, $request, requireActiveService: false);
|
||||
if ($vm instanceof JsonResponse) {
|
||||
return $vm;
|
||||
}
|
||||
@@ -462,60 +533,6 @@ class VmController extends Controller
|
||||
// Shared helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Load a ModuleVmware by ID (int), vmware_id (string), or Service UUID.
|
||||
* Verify the authenticated user owns it.
|
||||
* Returns JsonResponse on error, ModuleVmware on success.
|
||||
*/
|
||||
private function resolveVmById(int|string $productId, Request $request): ModuleVmware|JsonResponse
|
||||
{
|
||||
$customer = $request->user();
|
||||
$vm = null;
|
||||
|
||||
// Check if it's a UUID (Service UUID)
|
||||
if (is_string($productId) && preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i', $productId)) {
|
||||
$service = Service::with('vmware.ipAddress.host.datacenter.vCenter', 'vmware.vCenter')
|
||||
->where('uuid', $productId)
|
||||
->where('customer_id', $customer->id)
|
||||
->first();
|
||||
if ($service && $service->vmware) {
|
||||
$vm = $service->vmware;
|
||||
}
|
||||
} elseif (is_numeric($productId)) {
|
||||
// Numeric ID
|
||||
$vm = ModuleVmware::with(['vCenter', 'ipAddress.host.datacenter.vCenter'])
|
||||
->where('id', (int) $productId)
|
||||
->where('customer_id', $customer->id)
|
||||
->first();
|
||||
} else {
|
||||
// vmware_id string (e.g., "vm-3238")
|
||||
$vm = ModuleVmware::with(['vCenter', 'ipAddress.host.datacenter.vCenter'])
|
||||
->where('vmware_id', $productId)
|
||||
->where('customer_id', $customer->id)
|
||||
->first();
|
||||
}
|
||||
|
||||
if (!$vm) {
|
||||
return response()->json(['success' => false, 'message' => 'Không tìm thấy VM.'], 404);
|
||||
}
|
||||
|
||||
if ((int) $vm->customer_id !== (int) $customer->id) {
|
||||
return response()->json(['success' => false, 'message' => 'Bạn không có quyền thao tác VM này.'], 403);
|
||||
}
|
||||
|
||||
return $vm;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a ModuleVmware by ID, verify the authenticated user owns it.
|
||||
* Returns JsonResponse on error, ModuleVmware on success.
|
||||
* @deprecated Use resolveVmById instead for better ID format support
|
||||
*/
|
||||
private function resolveVm(int $id, Request $request): ModuleVmware|JsonResponse
|
||||
{
|
||||
return $this->resolveVmById($id, $request);
|
||||
}
|
||||
|
||||
/** Try to acquire a per-VM operation lock. Returns null if already locked. */
|
||||
private function acquireVmLock(ModuleVmware $vm, int $ttl = 60): ?\Illuminate\Contracts\Cache\Lock
|
||||
{
|
||||
|
||||
@@ -2,15 +2,22 @@
|
||||
|
||||
namespace App\Http\Controllers\Api\Service;
|
||||
|
||||
use App\Enums\Invoice\InvoiceStatus;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Controllers\Api\Service\Concerns\ResolvesVm;
|
||||
use App\Http\Services\vCenter;
|
||||
use App\Helpers\OrderHelper;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\InvoiceItem;
|
||||
use App\Models\Service;
|
||||
use App\Services\ActivityLogger;
|
||||
use App\Services\InvoicePaymentService;
|
||||
use App\Services\VirtualMachine\Rebuild\VmRebuildService;
|
||||
use App\Support\AddonQuantityValidator;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Throwable;
|
||||
|
||||
class VmRebuildController extends Controller
|
||||
@@ -103,7 +110,7 @@ class VmRebuildController extends Controller
|
||||
|
||||
return response()->json([
|
||||
'error' => true,
|
||||
'message' => 'Không thể gửi yêu cầu rebuild: ' . $e->getMessage(),
|
||||
'message' => 'Không thể gửi yêu cầu rebuild, vui lòng thử lại sau.',
|
||||
], 400);
|
||||
}
|
||||
|
||||
@@ -179,7 +186,9 @@ class VmRebuildController extends Controller
|
||||
]);
|
||||
}
|
||||
|
||||
public function upgradeAddons(Request $request, vCenter $serviceVCenter): JsonResponse
|
||||
private const INVOICE_TYPE_UPGRADE = 3;
|
||||
|
||||
public function upgradeAddons(Request $request): JsonResponse
|
||||
{
|
||||
$customer = $request->user();
|
||||
$payload = $request->validate([
|
||||
@@ -188,7 +197,7 @@ class VmRebuildController extends Controller
|
||||
'ram' => ['nullable', 'integer', 'min:0'],
|
||||
'disk' => ['nullable', 'integer', 'min:0'],
|
||||
'bandwidth' => ['nullable', 'integer', 'min:0'],
|
||||
'gpu' => ['nullable'],
|
||||
'gpu' => ['nullable', 'integer', 'min:0'],
|
||||
]);
|
||||
|
||||
$vm = $this->resolveVmById($payload['product'], $request);
|
||||
@@ -196,49 +205,160 @@ class VmRebuildController extends Controller
|
||||
return $vm;
|
||||
}
|
||||
|
||||
$vm->loadMissing(['vCenter', 'ipAddress.host.datacenter.vCenter']);
|
||||
$vm->loadMissing(['order.orderItems.product']);
|
||||
|
||||
$vcenter = $vm->vCenter ?? $vm->ipAddress?->host?->datacenter?->vCenter;
|
||||
if (!$vcenter || !$serviceVCenter->loginServer($vcenter)) {
|
||||
return response()->json(['error' => true, 'message' => 'Không thể đăng nhập vCenter'], 400);
|
||||
$orderItem = $vm->order?->orderItems?->first();
|
||||
$product = $orderItem?->product;
|
||||
if (!$orderItem || !$product) {
|
||||
return response()->json(['error' => true, 'message' => 'Không tìm thấy product của dịch vụ hiện tại'], 404);
|
||||
}
|
||||
|
||||
$applied = [];
|
||||
$service = Service::where('order_item_id', $orderItem->id)->first();
|
||||
if (!$service) {
|
||||
return response()->json(['error' => true, 'message' => 'Không tìm thấy dịch vụ hiện tại'], 404);
|
||||
}
|
||||
|
||||
if (isset($payload['cpu']) && $payload['cpu'] > 0) {
|
||||
$res = $serviceVCenter->UpgradeCPUVirtualMachine($vm->vmware_id, (int) $payload['cpu']);
|
||||
if (is_array($res) && !($res['error'] ?? true)) {
|
||||
$applied[] = 'cpu';
|
||||
}
|
||||
$requestedQtyByCode = array_filter([
|
||||
'cpu' => (int) ($payload['cpu'] ?? 0),
|
||||
'ram' => (int) ($payload['ram'] ?? 0),
|
||||
'disk' => (int) ($payload['disk'] ?? 0),
|
||||
'bandwidth' => (int) ($payload['bandwidth'] ?? 0),
|
||||
'gpu' => (int) ($payload['gpu'] ?? 0),
|
||||
], fn ($qty) => $qty > 0);
|
||||
|
||||
if (empty($requestedQtyByCode)) {
|
||||
return response()->json(['error' => true, 'message' => 'Vui lòng chọn ít nhất một addon để nâng cấp'], 422);
|
||||
}
|
||||
if (isset($payload['ram']) && $payload['ram'] > 0) {
|
||||
$res = $serviceVCenter->UpgradeMemoryVirtualMachine($vm->vmware_id, (int) $payload['ram']);
|
||||
if (is_array($res) && !($res['error'] ?? true)) {
|
||||
$applied[] = 'ram';
|
||||
|
||||
$activeAddons = $product->addons()->where('status', true)->get()->keyBy('id');
|
||||
$addonsByCode = $activeAddons->keyBy(fn ($addon) => strtolower((string) $addon->code));
|
||||
|
||||
$raw = [];
|
||||
foreach ($requestedQtyByCode as $code => $qty) {
|
||||
$addon = $addonsByCode->get($code);
|
||||
if (!$addon) {
|
||||
return response()->json(['error' => true, 'message' => "Addon \"{$code}\" không áp dụng cho sản phẩm này"], 422);
|
||||
}
|
||||
$raw[] = ['addon_id' => $addon->id, 'qty' => $qty];
|
||||
}
|
||||
if (isset($payload['disk']) && $payload['disk'] > 0) {
|
||||
$res = $serviceVCenter->UpgradeDiskVirtualMachine($vm, (int) $payload['disk']);
|
||||
if (is_array($res) && !($res['error'] ?? true)) {
|
||||
$applied[] = 'disk';
|
||||
}
|
||||
|
||||
$existingQtyByAddonId = collect(is_array($orderItem->addons_meta) ? $orderItem->addons_meta : [])
|
||||
->mapWithKeys(fn ($entry) => [(int) ($entry['addon_id'] ?? 0) => (int) ($entry['qty'] ?? 0)])
|
||||
->all();
|
||||
|
||||
try {
|
||||
$resolved = AddonQuantityValidator::resolve($raw, $activeAddons, $existingQtyByAddonId);
|
||||
} catch (ValidationException $e) {
|
||||
return response()->json([
|
||||
'error' => true,
|
||||
'message' => collect($e->errors())->flatten()->first() ?? 'Yêu cầu nâng cấp không hợp lệ',
|
||||
], 422);
|
||||
}
|
||||
|
||||
$existingInvoice = Invoice::where('service_id', $service->id)
|
||||
->where('invoice_type', self::INVOICE_TYPE_UPGRADE)
|
||||
->whereIn('status', InvoicePaymentService::PAYABLE_STATUSES)
|
||||
->first();
|
||||
|
||||
if ($existingInvoice) {
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'message' => 'Dịch vụ đã có hóa đơn nâng cấp đang chờ thanh toán.',
|
||||
'data' => $this->invoiceResponse($existingInvoice, $vm->order?->order_num),
|
||||
]);
|
||||
}
|
||||
|
||||
$cycleMonths = OrderHelper::cycleToMonths($orderItem->billing_cycle);
|
||||
$cycleDays = max(1, $cycleMonths * 30);
|
||||
$remainingDays = $service->expires_at && $service->expires_at->isFuture()
|
||||
? now()->diffInDays($service->expires_at)
|
||||
: 0;
|
||||
$remainingDays = (int) max(1, min($cycleDays, $remainingDays));
|
||||
|
||||
try {
|
||||
$invoice = DB::transaction(function () use ($service, $orderItem, $resolved, $remainingDays, $cycleDays) {
|
||||
$total = 0;
|
||||
$lines = [];
|
||||
|
||||
foreach ($resolved as $entry) {
|
||||
$unitPrice = $this->prorateUnitPrice((float) $entry['price'], $remainingDays, $cycleDays);
|
||||
$totalPrice = $unitPrice * $entry['qty'];
|
||||
$total += $totalPrice;
|
||||
|
||||
$lines[] = [
|
||||
'product_id' => $orderItem->product_id,
|
||||
'addon_id' => $entry['addon_id'],
|
||||
'type' => 'upgrade',
|
||||
'description' => 'Nâng cấp addon: ' . $entry['name'] . ' x' . $entry['qty'],
|
||||
'months' => 0,
|
||||
'quantity' => $entry['qty'],
|
||||
'unit_price' => $unitPrice,
|
||||
'total_price' => $totalPrice,
|
||||
];
|
||||
}
|
||||
|
||||
$invoice = Invoice::create([
|
||||
'invoice_number' => OrderHelper::generateOrderNumber('INV'),
|
||||
'customer_id' => $service->customer_id,
|
||||
'order_id' => $orderItem->order_id,
|
||||
'service_id' => $service->id,
|
||||
'invoice_type' => self::INVOICE_TYPE_UPGRADE,
|
||||
'sub_total' => $total,
|
||||
'discount_amount' => 0,
|
||||
'tax' => 0,
|
||||
'total' => $total,
|
||||
'status' => InvoiceStatus::UNPAID->value,
|
||||
'due_date' => now()->addDays(3)->toDateString(),
|
||||
]);
|
||||
|
||||
foreach ($lines as $line) {
|
||||
InvoiceItem::create($line + ['invoice_id' => $invoice->id]);
|
||||
}
|
||||
|
||||
return $invoice;
|
||||
});
|
||||
} catch (Throwable $e) {
|
||||
Log::error('VmRebuildController: upgradeAddons invoice creation failed', [
|
||||
'module_vmware_id' => $vm->id,
|
||||
'service_id' => $service->id,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return response()->json(['error' => true, 'message' => 'Không thể tạo yêu cầu nâng cấp, vui lòng thử lại sau.'], 500);
|
||||
}
|
||||
|
||||
$this->activityLogger->log(
|
||||
event: 'upgrade_addons',
|
||||
event: 'upgrade_addons_requested',
|
||||
logName: 'VM',
|
||||
description: "Customer {$customer->email} nâng cấp addons VM: {$vm->name} - áp dụng: " . implode(', ', $applied ?: ['none']),
|
||||
description: "Customer {$customer->email} yêu cầu nâng cấp addons VM: {$vm->name}, hóa đơn #{$invoice->invoice_number}",
|
||||
subject: $vm,
|
||||
newValues: array_filter(['cpu' => $payload['cpu'] ?? null, 'ram' => $payload['ram'] ?? null, 'disk' => $payload['disk'] ?? null]),
|
||||
newValues: ['invoice_id' => $invoice->id, 'addons' => $resolved],
|
||||
);
|
||||
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'message' => 'Đã gửi yêu cầu nâng cấp addons',
|
||||
'data' => [
|
||||
'applied' => $applied,
|
||||
'note' => 'bandwidth/gpu hiện được ghi nhận yêu cầu, chưa có luồng tự động áp vào VM',
|
||||
],
|
||||
'message' => 'Đã tạo hóa đơn nâng cấp. Vui lòng thanh toán để áp dụng vào VM.',
|
||||
'data' => $this->invoiceResponse($invoice, $vm->order?->order_num),
|
||||
]);
|
||||
}
|
||||
|
||||
private function prorateUnitPrice(float $price, int $remainingDays, int $cycleDays): int
|
||||
{
|
||||
$raw = $price * $remainingDays / $cycleDays;
|
||||
|
||||
return (int) (ceil($raw / 1000) * 1000);
|
||||
}
|
||||
|
||||
private function invoiceResponse(Invoice $invoice, ?string $orderNum): array
|
||||
{
|
||||
return [
|
||||
'order_id' => $invoice->order_id,
|
||||
'order_num' => $orderNum,
|
||||
'invoice_id' => $invoice->id,
|
||||
'invoice_number' => $invoice->invoice_number,
|
||||
'total' => (float) $invoice->total,
|
||||
'status' => $invoice->status,
|
||||
'payment_url' => $orderNum ? '/hoa-don/' . $orderNum : null,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -182,6 +182,18 @@ class ManualDepositController extends Controller
|
||||
|
||||
$user = $request->user();
|
||||
|
||||
if (
|
||||
!str_starts_with($request->proof_image, "deposit-proofs/{$user->id}/")
|
||||
|| str_contains($request->proof_image, '..')
|
||||
|| !Storage::disk('local')->exists($request->proof_image)
|
||||
|| Transaction::where('proof_image', $request->proof_image)->exists()
|
||||
) {
|
||||
return response()->json([
|
||||
'error' => true,
|
||||
'message' => 'Chứng từ không hợp lệ',
|
||||
], 422);
|
||||
}
|
||||
|
||||
$transaction = Transaction::where('uuid', $request->uuid)
|
||||
->where('customer_id', $user->id)
|
||||
->where('type', 'manual')
|
||||
@@ -254,14 +266,15 @@ class ManualDepositController extends Controller
|
||||
public function uploadProof(Request $request): JsonResponse
|
||||
{
|
||||
$request->validate([
|
||||
'file' => 'required|image|mimes:jpeg,jpg,png|max:5120',
|
||||
'file' => 'required|image|mimes:jpeg,jpg,png,webp|max:5120',
|
||||
]);
|
||||
|
||||
$path = $request->file('file')->store('deposit-proofs', 'public');
|
||||
$user = $request->user();
|
||||
|
||||
$path = $request->file('file')->store('deposit-proofs/' . $user->id, 'local');
|
||||
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'url' => Storage::disk('public')->url($path),
|
||||
'path' => $path,
|
||||
]);
|
||||
}
|
||||
@@ -288,7 +301,7 @@ class ManualDepositController extends Controller
|
||||
'client_ip' => $request->ip(),
|
||||
'transaction_code' => $transaction->public_code,
|
||||
'amount' => $transaction->amount,
|
||||
'proof_image_url' => $transaction->proof_image ? Storage::disk('public')->url($transaction->proof_image) : null,
|
||||
'proof_image_url' => $transaction->proof_image_urls[0] ?? null,
|
||||
'created_at' => now()->format('d/m/Y H:i:s'),
|
||||
]));
|
||||
} catch (\Throwable $e) {
|
||||
|
||||
@@ -15,7 +15,7 @@ use App\Repositories\Module\IpAddress\IpAddressRepositoryInterface;
|
||||
use App\Repositories\Module\Network\NetworkRepositoryInterface;
|
||||
use App\Repositories\vCenter\vCenterRepositoryInterface;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use App\Support\TlsHttpClientFactory;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Yajra\DataTables\Facades\DataTables;
|
||||
|
||||
@@ -495,7 +495,7 @@ class VCenterManagerController extends Controller
|
||||
return response()->json(['error' => true, 'message' => 'Cannot login to vCenter'], 400);
|
||||
}
|
||||
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $vCenterService->token
|
||||
])
|
||||
@@ -555,7 +555,7 @@ class VCenterManagerController extends Controller
|
||||
return response()->json(['error' => true, 'message' => 'Cannot login to vCenter'], 400);
|
||||
}
|
||||
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $vCenterService->token
|
||||
])
|
||||
@@ -603,7 +603,7 @@ class VCenterManagerController extends Controller
|
||||
return response()->json(['error' => true, 'message' => 'Cannot login to vCenter'], 400);
|
||||
}
|
||||
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders(['vmware-api-session-id' => $vCenterService->token])
|
||||
->post("https://{$vCenterService->apiUri}/rest/vcenter/vm/$vmwareId/power/reset");
|
||||
|
||||
@@ -652,7 +652,7 @@ class VCenterManagerController extends Controller
|
||||
return response()->json(['error' => true, 'message' => 'Cannot login to vCenter'], 400);
|
||||
}
|
||||
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders(['vmware-api-session-id' => $vCenterService->token])
|
||||
->post("https://{$vCenterService->apiUri}/rest/vcenter/vm/$vmwareId/snapshot", [
|
||||
'spec' => [
|
||||
@@ -800,7 +800,7 @@ class VCenterManagerController extends Controller
|
||||
return response()->json(['error' => true, 'message' => 'Cannot login to vCenter'], 400);
|
||||
}
|
||||
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders(['vmware-api-session-id' => $vCenterService->token])
|
||||
->post("https://{$vCenterService->apiUri}/rest/vcenter/vm/$vmwareId/power/suspend");
|
||||
|
||||
|
||||
@@ -91,6 +91,7 @@ class Kernel extends HttpKernel
|
||||
'api.auth' => \App\Http\Middleware\ApiAuthCheck::class,
|
||||
'client.access-token' => \App\Http\Middleware\ClientAccessTokenCheck::class,
|
||||
'perm' => \App\Http\Middleware\CheckPermission::class,
|
||||
'restrict.local' => \App\Http\Middleware\RestrictToLocalEnvironment::class,
|
||||
'compression' => \App\Http\Middleware\CompressionMiddleware::class,
|
||||
'compression.advanced' => \App\Http\Middleware\AdvancedCompressionMiddleware::class,
|
||||
];
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class RestrictToLocalEnvironment
|
||||
{
|
||||
public function handle(Request $request, Closure $next): mixed
|
||||
{
|
||||
if (!app()->environment('local')) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Http\Requests\Api\Client;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rules\Password;
|
||||
|
||||
class ClientChangePasswordRequest extends FormRequest
|
||||
{
|
||||
@@ -15,7 +16,7 @@ class ClientChangePasswordRequest extends FormRequest
|
||||
{
|
||||
return [
|
||||
'current_password' => 'required|string',
|
||||
'password' => 'required|string|min:8|confirmed|different:current_password',
|
||||
'password' => ['required', Password::min(10), 'confirmed', 'different:current_password'],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -24,7 +25,7 @@ class ClientChangePasswordRequest extends FormRequest
|
||||
return [
|
||||
'current_password.required' => 'Mật khẩu hiện tại là bắt buộc',
|
||||
'password.required' => 'Mật khẩu mới là bắt buộc',
|
||||
'password.min' => 'Mật khẩu mới phải có ít nhất 8 ký tự',
|
||||
'password.min' => 'Mật khẩu mới phải có ít nhất 10 ký tự',
|
||||
'password.confirmed' => 'Xác nhận mật khẩu không khớp',
|
||||
'password.different' => 'Mật khẩu mới phải khác mật khẩu hiện tại',
|
||||
];
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Http\Requests\Api\Client;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rules\Password;
|
||||
|
||||
class ClientRegisterRequest extends FormRequest
|
||||
{
|
||||
@@ -40,8 +41,7 @@ class ClientRegisterRequest extends FormRequest
|
||||
|
||||
'password' => [
|
||||
'required',
|
||||
'string',
|
||||
'min:6',
|
||||
Password::min(10),
|
||||
'confirmed'
|
||||
],
|
||||
|
||||
@@ -67,7 +67,7 @@ class ClientRegisterRequest extends FormRequest
|
||||
'email.unique' => 'Email đã tồn tại',
|
||||
|
||||
'password.required' => 'Mật khẩu là bắt buộc',
|
||||
'password.min' => 'Mật khẩu tối thiểu 6 ký tự',
|
||||
'password.min' => 'Mật khẩu tối thiểu 10 ký tự',
|
||||
'password.confirmed' => 'Xác nhận mật khẩu không khớp',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -15,8 +15,8 @@ class ClientUpdateCccdRequest extends FormRequest
|
||||
{
|
||||
return [
|
||||
'cmnd' => 'required|string|max:50',
|
||||
'cmnd_before' => 'required|image|max:5120',
|
||||
'cmnd_after' => 'required|image|max:5120',
|
||||
'cmnd_before' => 'required|mimes:jpg,jpeg,png,webp|max:5120',
|
||||
'cmnd_after' => 'required|mimes:jpg,jpeg,png,webp|max:5120',
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ class RenewServiceRequest extends FormRequest
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'months' => ['required', 'integer', 'min:1', 'max:24'],
|
||||
'months' => ['required', 'integer', 'min:1', 'max:36'],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ class RenewServiceRequest extends FormRequest
|
||||
'months.required' => 'Vui lòng chọn số tháng gia hạn.',
|
||||
'months.integer' => 'Số tháng gia hạn không hợp lệ.',
|
||||
'months.min' => 'Số tháng gia hạn tối thiểu là 1.',
|
||||
'months.max' => 'Số tháng gia hạn tối đa là 24.',
|
||||
'months.max' => 'Số tháng gia hạn tối đa là 36.',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ class StoreOrderRequest extends FormRequest
|
||||
'os_id' => 'nullable|integer',
|
||||
'addons' => 'array',
|
||||
'addons.*.addon_id' => 'nullable|exists:product_addon,id',
|
||||
'addons.*.qty' => 'nullable|integer|min:0',
|
||||
'addons.*.qty' => 'nullable|integer|min:0|max:1000000',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -38,6 +38,7 @@ class StoreOrderRequest extends FormRequest
|
||||
'os_id.exists' => 'Hệ điều hành không hợp lệ',
|
||||
'addons.*.addon_id.exists' => 'Addon không tồn tại',
|
||||
'addons.*.qty.min' => 'Số lượng addon phải lớn hơn 0',
|
||||
'addons.*.qty.max' => 'Số lượng addon vượt quá giới hạn cho phép',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ class InvoiceResource extends JsonResource
|
||||
'order_num' => $this->whenLoaded('order', fn() => $this->order?->order_num),
|
||||
'customer' => $this->whenLoaded('customer', fn() => [
|
||||
'id' => $this->customer->id,
|
||||
'uuid' => $this->customer->uuid,
|
||||
'fullname' => $this->customer->fullname,
|
||||
'email' => $this->customer->email,
|
||||
]),
|
||||
|
||||
@@ -90,6 +90,7 @@ class ServiceClientDetailResource extends JsonResource
|
||||
'total' => (float) $order->total,
|
||||
'months' => (int) $orderItem->months,
|
||||
'billing_label' => $orderItem->billing_label,
|
||||
'addon_total' => \App\Support\RenewalPricing::addonTotal($this->resource, 1),
|
||||
] : null,
|
||||
'vm' => $vm ? [
|
||||
'id' => $vm->id,
|
||||
|
||||
@@ -15,33 +15,33 @@ class ServiceResource extends JsonResource
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$billingCycleLabels = [
|
||||
'monthly' => 'Hàng tháng',
|
||||
'quarterly' => 'Hàng quý',
|
||||
'semiannually' => 'Nửa năm',
|
||||
'annually' => 'Hàng năm',
|
||||
'biennially' => '2 năm',
|
||||
'triennially' => '3 năm',
|
||||
'onetime' => 'Một lần',
|
||||
'monthly' => 'Hàng tháng',
|
||||
'quarterly' => 'Hàng quý',
|
||||
'semi_annually' => 'Nửa năm',
|
||||
'annually' => 'Hàng năm',
|
||||
'biennially' => '2 năm',
|
||||
'triennially' => '3 năm',
|
||||
'onetime' => 'Một lần',
|
||||
];
|
||||
|
||||
$periodUnits = [
|
||||
'monthly' => 'month',
|
||||
'quarterly' => 'quarter',
|
||||
'semiannually' => 'semi_year',
|
||||
'annually' => 'year',
|
||||
'biennially' => 'biennially',
|
||||
'triennially' => 'triennially',
|
||||
'onetime' => 'none',
|
||||
'monthly' => 'month',
|
||||
'quarterly' => 'quarter',
|
||||
'semi_annually' => 'semi_year',
|
||||
'annually' => 'year',
|
||||
'biennially' => 'biennially',
|
||||
'triennially' => 'triennially',
|
||||
'onetime' => 'none',
|
||||
];
|
||||
|
||||
$periodMonths = [
|
||||
'monthly' => 1,
|
||||
'quarterly' => 3,
|
||||
'semiannually' => 6,
|
||||
'annually' => 12,
|
||||
'biennially' => 24,
|
||||
'triennially' => 36,
|
||||
'onetime' => 0,
|
||||
'monthly' => 1,
|
||||
'quarterly' => 3,
|
||||
'semi_annually' => 6,
|
||||
'annually' => 12,
|
||||
'biennially' => 24,
|
||||
'triennially' => 36,
|
||||
'onetime' => 0,
|
||||
];
|
||||
|
||||
return [
|
||||
|
||||
@@ -5,7 +5,7 @@ namespace App\Http\Services;
|
||||
use App\Models\ModuleHosting;
|
||||
use App\Support\Eloquent\Sluggable;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use App\Support\TlsHttpClientFactory;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ class Hosting
|
||||
|
||||
if ($apiCheck) {
|
||||
|
||||
return Http::withoutVerifying()
|
||||
return TlsHttpClientFactory::plesk()
|
||||
->withHeaders([
|
||||
'X-API-Key' => $this->apiKey,
|
||||
'accept' => 'application/json'
|
||||
@@ -47,7 +47,7 @@ class Hosting
|
||||
Log::info('Không tồn tại apiKey');
|
||||
return false;
|
||||
}
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::plesk()
|
||||
->withHeaders([
|
||||
'X-API-Key' => $this->apiKey,
|
||||
'accept' => 'application/json'
|
||||
@@ -64,7 +64,7 @@ class Hosting
|
||||
*/
|
||||
public function LoginServer(): array
|
||||
{
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::plesk()
|
||||
->withBasicAuth($this->username, $this->password)
|
||||
->acceptJson()
|
||||
->post("https://$this->url/api/v2/auth/keys",
|
||||
@@ -127,7 +127,7 @@ class Hosting
|
||||
*/
|
||||
public function getAllClients()
|
||||
{
|
||||
return Http::withoutVerifying()
|
||||
return TlsHttpClientFactory::plesk()
|
||||
->withHeaders([
|
||||
'X-API-Key' => $this->apiKey,
|
||||
'accept' => 'application/json'
|
||||
@@ -137,7 +137,7 @@ class Hosting
|
||||
|
||||
public function CreateNewClient($product_data = [], $password = ''): array
|
||||
{
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::plesk()
|
||||
->withHeaders([
|
||||
'X-API-Key' => $this->apiKey,
|
||||
'accept' => 'application/json'
|
||||
@@ -202,7 +202,7 @@ class Hosting
|
||||
|
||||
if ($apiCheck) {
|
||||
|
||||
$allDomain = Http::withoutVerifying()
|
||||
$allDomain = TlsHttpClientFactory::plesk()
|
||||
->withHeaders([
|
||||
'X-API-Key' => $this->apiKey,
|
||||
'accept' => 'application/json'
|
||||
@@ -234,7 +234,7 @@ class Hosting
|
||||
|
||||
if ($apiCheck) {
|
||||
|
||||
$CreateDomain = Http::withoutVerifying()
|
||||
$CreateDomain = TlsHttpClientFactory::plesk()
|
||||
->withHeaders([
|
||||
'X-API-Key' => $this->apiKey,
|
||||
'accept' => 'application/json'
|
||||
@@ -276,7 +276,7 @@ class Hosting
|
||||
|
||||
public function CreateExpirationForDomain($domain = '', $date_exp = '')
|
||||
{
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::plesk()
|
||||
->withHeaders([
|
||||
'X-API-Key' => $this->apiKey,
|
||||
'accept' => 'application/json'
|
||||
@@ -303,7 +303,7 @@ class Hosting
|
||||
|
||||
public function SuspendAccount($account_id = 0): array
|
||||
{
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::plesk()
|
||||
->withHeaders([
|
||||
'X-API-Key' => $this->apiKey,
|
||||
'accept' => 'application/json'
|
||||
@@ -322,7 +322,7 @@ class Hosting
|
||||
|
||||
public function ActivateAccount($account_id = 0): array
|
||||
{
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::plesk()
|
||||
->withHeaders([
|
||||
'X-API-Key' => $this->apiKey,
|
||||
'accept' => 'application/json'
|
||||
@@ -341,7 +341,7 @@ class Hosting
|
||||
|
||||
public function ResetPassword($account_id = 0, $password = ''): array
|
||||
{
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::plesk()
|
||||
->withHeaders([
|
||||
'X-API-Key' => $this->apiKey,
|
||||
'accept' => 'application/json'
|
||||
|
||||
@@ -7,13 +7,16 @@ class SignRSA
|
||||
protected string $key;
|
||||
protected ?string $private;
|
||||
protected string $public;
|
||||
protected ?string $previousKey;
|
||||
protected ?string $previousPublic;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->key = base64_decode(config('rsa.key'));
|
||||
$this->private = str_replace('\n', "\n", config('rsa.private'));
|
||||
$this->public = str_replace('\n', "\n", config('rsa.public'));
|
||||
|
||||
$this->previousKey = config('rsa.previous_key') ? base64_decode(config('rsa.previous_key')) : null;
|
||||
$this->previousPublic = config('rsa.previous_public') ? str_replace('\n', "\n", config('rsa.previous_public')) : null;
|
||||
}
|
||||
|
||||
|
||||
@@ -49,9 +52,14 @@ class SignRSA
|
||||
if (!$data) {
|
||||
return false;
|
||||
}
|
||||
$decrypted_data = $this->DecryptData(base64_decode($data), $this->key);
|
||||
$encrypted_data = base64_decode($data);
|
||||
$verified = $this->Verify_Sign((string) $this->DecryptData($encrypted_data, $this->key), $this->public);
|
||||
|
||||
return $this->Verify_Sign($decrypted_data);
|
||||
if ($verified === false && $this->previousKey && $this->previousPublic) {
|
||||
$verified = $this->Verify_Sign((string) $this->DecryptData($encrypted_data, $this->previousKey), $this->previousPublic);
|
||||
}
|
||||
|
||||
return $verified;
|
||||
}
|
||||
|
||||
private function DecryptData($encrypted_data, $random_key): bool|string
|
||||
@@ -59,7 +67,7 @@ class SignRSA
|
||||
return openssl_decrypt($encrypted_data, 'DES-EDE3', $random_key, OPENSSL_RAW_DATA);
|
||||
}
|
||||
|
||||
private function Verify_Sign($decrypted_data): array|string|false
|
||||
private function Verify_Sign(string $decrypted_data, string $public): string|false
|
||||
{
|
||||
$data_arr = explode('|', $decrypted_data);
|
||||
|
||||
@@ -67,19 +75,15 @@ class SignRSA
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!isset($data_arr[1])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$signature = base64_decode($data_arr[1]);
|
||||
|
||||
unset($data_arr[1]);
|
||||
|
||||
$signature_data = implode('|', $data_arr);
|
||||
|
||||
$verify = openssl_verify($signature_data, $signature, $this->public, 'sha256WithRSAEncryption');
|
||||
$verify = openssl_verify($signature_data, $signature, $public, 'sha256WithRSAEncryption');
|
||||
|
||||
return $verify ? $signature_data : false;
|
||||
return $verify === 1 ? $signature_data : false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ class Telegram
|
||||
|
||||
try {
|
||||
$url = "https://api.telegram.org/bot$this->token/sendMessage?parse_mode=html&chat_id=$this->group&text=" . urlencode($message);
|
||||
$response = Http::withoutVerifying()->get($url);
|
||||
$response = Http::get($url);
|
||||
|
||||
// Log response để debug
|
||||
Log::channel('Custom')->info('Telegram sendMessage URL: ' . $url);
|
||||
@@ -234,8 +234,7 @@ class Telegram
|
||||
'contents' => $caption,
|
||||
];
|
||||
}
|
||||
$response = Http::withoutVerifying()
|
||||
->attach('photo', fopen($fullPath, 'r'), basename($fullPath))
|
||||
$response = Http::attach('photo', fopen($fullPath, 'r'), basename($fullPath))
|
||||
->post("https://api.telegram.org/bot{$this->token}/sendPhoto", [
|
||||
'chat_id' => $this->group,
|
||||
'caption' => $caption,
|
||||
|
||||
@@ -1,253 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Services;
|
||||
|
||||
use Illuminate\Support\Facades\Http;
|
||||
|
||||
class WinRMClient
|
||||
{
|
||||
private $ip;
|
||||
private $username;
|
||||
private $password;
|
||||
private $url;
|
||||
private $auth;
|
||||
|
||||
public function __construct($ip, $username, $password)
|
||||
{
|
||||
$this->ip = $ip;
|
||||
$this->username = $username;
|
||||
$this->password = $password;
|
||||
$this->url = "http://{$this->ip}:53389/wsman";
|
||||
$this->auth = base64_encode("{$this->username}:{$this->password}");
|
||||
}
|
||||
|
||||
private function send_winrm_request($headers, $body)
|
||||
{
|
||||
try {
|
||||
// Make the HTTP POST request
|
||||
$response = Http::withHeaders($headers)
|
||||
->withBasicAuth('administrator', 'Thegioiso@123**$$8899TgTk2')
|
||||
->timeout(20) // Timeout in seconds
|
||||
->withBody($body, 'application/soap+xml;charset=UTF-8') // Ensure the correct content type
|
||||
->withoutVerifying() // Disable SSL verification
|
||||
->post($this->url);
|
||||
|
||||
// Check for a successful response
|
||||
if ($response->successful()) {
|
||||
return $response->body();
|
||||
}
|
||||
// Handle response errors
|
||||
return 'Error: ' . $response->status() . ' - ' . $response->body();
|
||||
} catch (\Exception $e) {
|
||||
// Handle exceptions
|
||||
return 'Exception: ' . $e->getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
private function get_headers()
|
||||
{
|
||||
return [
|
||||
"Host: {$this->ip}:53389",
|
||||
"User-Agent: PHP WinRM client",
|
||||
"Accept-Encoding: gzip, deflate, br",
|
||||
"Accept: */*",
|
||||
"Connection: keep-alive",
|
||||
"Content-Type: application/soap+xml;charset=UTF-8",
|
||||
"Authorization: Basic {$this->auth}"
|
||||
];
|
||||
}
|
||||
|
||||
public function execute_command($command)
|
||||
{
|
||||
$headers = $this->get_headers();
|
||||
|
||||
// Step 1: Create Shell
|
||||
$create_shell_body = $this->get_create_shell_body();
|
||||
$response = $this->send_winrm_request($headers, $create_shell_body);
|
||||
$shell_id = preg_match('/<rsp:ShellId>(.*?)<\/rsp:ShellId>/s', $response, $matches) ? $matches[1] : null;
|
||||
|
||||
if (!$shell_id) {
|
||||
return "Failed to create shell session.";
|
||||
}
|
||||
|
||||
// Step 2: Execute Command
|
||||
$execute_command_body = $this->get_execute_command_body($shell_id, $command);
|
||||
$response = $this->send_winrm_request($headers, $execute_command_body);
|
||||
$command_id = preg_match('/<rsp:CommandId>(.*?)<\/rsp:CommandId>/s', $response, $matches) ? $matches[1] : null;
|
||||
|
||||
if (!$command_id) {
|
||||
return "Failed to execute command.";
|
||||
}
|
||||
|
||||
// Step 3: Receive Command Output
|
||||
$receive_output_body = $this->get_receive_output_body($shell_id, $command_id);
|
||||
$response = $this->send_winrm_request($headers, $receive_output_body);
|
||||
$output = $this->parse_command_output($response, $command_id);
|
||||
|
||||
// Step 4: Signal Termination
|
||||
$signal_termination_body = $this->get_signal_termination_body($shell_id, $command_id);
|
||||
$this->send_winrm_request($headers, $signal_termination_body);
|
||||
|
||||
// Step 5: Delete Shell Session
|
||||
$delete_shell_body = $this->get_delete_shell_body($shell_id);
|
||||
$this->send_winrm_request($headers, $delete_shell_body);
|
||||
|
||||
return $output;
|
||||
}
|
||||
|
||||
private function get_create_shell_body()
|
||||
{
|
||||
// XML body for creating a shell
|
||||
return '<?xml version="1.0" encoding="utf-8"?>
|
||||
<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:b="http://schemas.dmtf.org/wbem/wsman/1/cimbinding.xsd" xmlns:n="http://schemas.xmlsoap.org/ws/2004/09/enumeration" xmlns:x="http://schemas.xmlsoap.org/ws/2004/09/transfer" xmlns:w="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd" xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wsman.xsd" xmlns:rsp="http://schemas.microsoft.com/wbem/wsman/1/windows/shell" xmlns:cfg="http://schemas.microsoft.com/wbem/wsman/1/config">
|
||||
<env:Header>
|
||||
<a:To>http://' . $this->ip . ':53389/wsman</a:To>
|
||||
<a:ReplyTo>
|
||||
<a:Address mustUnderstand="true">http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address>
|
||||
</a:ReplyTo>
|
||||
<w:MaxEnvelopeSize mustUnderstand="true">153600</w:MaxEnvelopeSize>
|
||||
<a:MessageID>uuid:' . uniqid() . '</a:MessageID>
|
||||
<w:Locale mustUnderstand="false" xml:lang="en-US"/>
|
||||
<p:DataLocale mustUnderstand="false" xml:lang="en-US"/>
|
||||
<w:OperationTimeout>PT60S</w:OperationTimeout>
|
||||
<w:ResourceURI mustUnderstand="true">http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd</w:ResourceURI>
|
||||
<a:Action mustUnderstand="true">http://schemas.xmlsoap.org/ws/2004/09/transfer/Create</a:Action>
|
||||
<w:OptionSet>
|
||||
<w:Option Name="WINRS_NOPROFILE">FALSE</w:Option>
|
||||
<w:Option Name="WINRS_CODEPAGE">437</w:Option>
|
||||
</w:OptionSet>
|
||||
</env:Header>
|
||||
<env:Body>
|
||||
<rsp:Shell>
|
||||
<rsp:InputStreams>stdin</rsp:InputStreams>
|
||||
<rsp:OutputStreams>stdout stderr</rsp:OutputStreams>
|
||||
</rsp:Shell>
|
||||
</env:Body>
|
||||
</env:Envelope>';
|
||||
}
|
||||
|
||||
private function get_execute_command_body($shell_id, $command)
|
||||
{
|
||||
// XML body for executing a command
|
||||
return '<?xml version="1.0" encoding="utf-8"?>
|
||||
<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:b="http://schemas.dmtf.org/wbem/wsman/1/cimbinding.xsd" xmlns:n="http://schemas.xmlsoap.org/ws/2004/09/enumeration" xmlns:x="http://schemas.xmlsoap.org/ws/2004/09/transfer" xmlns:w="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd" xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wsman.xsd" xmlns:rsp="http://schemas.microsoft.com/wbem/wsman/1/windows/shell" xmlns:cfg="http://schemas.microsoft.com/wbem/wsman/1/config">
|
||||
<env:Header>
|
||||
<a:To>http://' . $this->ip . ':53389/wsman</a:To>
|
||||
<a:ReplyTo>
|
||||
<a:Address mustUnderstand="true">http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address>
|
||||
</a:ReplyTo>
|
||||
<w:MaxEnvelopeSize mustUnderstand="true">153600</w:MaxEnvelopeSize>
|
||||
<a:MessageID>uuid:' . uniqid() . '</a:MessageID>
|
||||
<w:Locale mustUnderstand="false" xml:lang="en-US"/>
|
||||
<p:DataLocale mustUnderstand="false" xml:lang="en-US"/>
|
||||
<w:OperationTimeout>PT60S</w:OperationTimeout>
|
||||
<w:ResourceURI mustUnderstand="true">http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd</w:ResourceURI>
|
||||
<a:Action mustUnderstand="true">http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Command</a:Action>
|
||||
<w:SelectorSet>
|
||||
<w:Selector Name="ShellId">' . $shell_id . '</w:Selector>
|
||||
</w:SelectorSet>
|
||||
</env:Header>
|
||||
<env:Body>
|
||||
<rsp:CommandLine>
|
||||
<rsp:Command>' . $command . '</rsp:Command>
|
||||
</rsp:CommandLine>
|
||||
</env:Body>
|
||||
</env:Envelope>';
|
||||
}
|
||||
|
||||
private function get_receive_output_body($shell_id, $command_id)
|
||||
{
|
||||
// XML body for receiving command output
|
||||
return '<?xml version="1.0" encoding="utf-8"?>
|
||||
<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:b="http://schemas.dmtf.org/wbem/wsman/1/cimbinding.xsd" xmlns:n="http://schemas.xmlsoap.org/ws/2004/09/enumeration" xmlns:x="http://schemas.xmlsoap.org/ws/2004/09/transfer" xmlns:w="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd" xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wsman.xsd" xmlns:rsp="http://schemas.microsoft.com/wbem/wsman/1/windows/shell" xmlns:cfg="http://schemas.microsoft.com/wbem/wsman/1/config">
|
||||
<env:Header>
|
||||
<a:To>http://' . $this->ip . ':53389/wsman</a:To>
|
||||
<a:ReplyTo>
|
||||
<a:Address mustUnderstand="true">http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address>
|
||||
</a:ReplyTo>
|
||||
<w:MaxEnvelopeSize mustUnderstand="true">153600</w:MaxEnvelopeSize>
|
||||
<a:MessageID>uuid:' . uniqid() . '</a:MessageID>
|
||||
<w:Locale mustUnderstand="false" xml:lang="en-US"/>
|
||||
<p:DataLocale mustUnderstand="false" xml:lang="en-US"/>
|
||||
<w:OperationTimeout>PT60S</w:OperationTimeout>
|
||||
<w:ResourceURI mustUnderstand="true">http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd</w:ResourceURI>
|
||||
<a:Action mustUnderstand="true">http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Receive</a:Action>
|
||||
<w:SelectorSet>
|
||||
<w:Selector Name="ShellId">' . $shell_id . '</w:Selector>
|
||||
</w:SelectorSet>
|
||||
</env:Header>
|
||||
<env:Body>
|
||||
<rsp:Receive>
|
||||
<rsp:DesiredStream CommandId="' . $command_id . '">stdout stderr</rsp:DesiredStream>
|
||||
</rsp:Receive>
|
||||
</env:Body>
|
||||
</env:Envelope>';
|
||||
}
|
||||
|
||||
private function parse_command_output($response, $command_id)
|
||||
{
|
||||
preg_match_all('/<rsp:Stream Name="stdout" CommandId="' . $command_id . '">(.*?)<\/rsp:Stream>/s', $response, $matches);
|
||||
$output = '';
|
||||
foreach ($matches[1] as $base64_output) {
|
||||
$decoded = base64_decode($base64_output);
|
||||
// Normalize line endings to \n
|
||||
$decoded = preg_replace('/\r\n|\r/', "\n", $decoded);
|
||||
$output .= $decoded;
|
||||
}
|
||||
return trim($output); // Remove any leading/trailing whitespace
|
||||
}
|
||||
|
||||
private function get_signal_termination_body($shell_id, $command_id)
|
||||
{
|
||||
// XML body for signaling termination
|
||||
return '<?xml version="1.0" encoding="utf-8"?>
|
||||
<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:b="http://schemas.dmtf.org/wbem/wsman/1/cimbinding.xsd" xmlns:n="http://schemas.xmlsoap.org/ws/2004/09/enumeration" xmlns:x="http://schemas.xmlsoap.org/ws/2004/09/transfer" xmlns:w="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd" xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wsman.xsd" xmlns:rsp="http://schemas.microsoft.com/wbem/wsman/1/windows/shell" xmlns:cfg="http://schemas.microsoft.com/wbem/wsman/1/config">
|
||||
<env:Header>
|
||||
<a:To>http://' . $this->ip . ':53389/wsman</a:To>
|
||||
<a:ReplyTo>
|
||||
<a:Address mustUnderstand="true">http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address>
|
||||
</a:ReplyTo>
|
||||
<w:MaxEnvelopeSize mustUnderstand="true">153600</w:MaxEnvelopeSize>
|
||||
<a:MessageID>uuid:' . uniqid() . '</a:MessageID>
|
||||
<w:Locale mustUnderstand="false" xml:lang="en-US"/>
|
||||
<p:DataLocale mustUnderstand="false" xml:lang="en-US"/>
|
||||
<w:OperationTimeout>PT60S</w:OperationTimeout>
|
||||
<w:ResourceURI mustUnderstand="true">http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd</w:ResourceURI>
|
||||
<a:Action mustUnderstand="true">http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Signal</a:Action>
|
||||
<w:SelectorSet>
|
||||
<w:Selector Name="ShellId">' . $shell_id . '</w:Selector>
|
||||
</w:SelectorSet>
|
||||
</env:Header>
|
||||
<env:Body>
|
||||
<rsp:Signal CommandId="' . $command_id . '">
|
||||
<rsp:Code>http://schemas.microsoft.com/wbem/wsman/1/windows/shell/signal/terminate</rsp:Code>
|
||||
</rsp:Signal>
|
||||
</env:Body>
|
||||
</env:Envelope>';
|
||||
}
|
||||
|
||||
private function get_delete_shell_body($shell_id)
|
||||
{
|
||||
// XML body for deleting the shell session
|
||||
return '<?xml version="1.0" encoding="utf-8"?>
|
||||
<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:b="http://schemas.dmtf.org/wbem/wsman/1/cimbinding.xsd" xmlns:n="http://schemas.xmlsoap.org/ws/2004/09/enumeration" xmlns:x="http://schemas.xmlsoap.org/ws/2004/09/transfer" xmlns:w="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd" xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wsman.xsd" xmlns:rsp="http://schemas.microsoft.com/wbem/wsman/1/windows/shell" xmlns:cfg="http://schemas.microsoft.com/wbem/wsman/1/config">
|
||||
<env:Header>
|
||||
<a:To>http://' . $this->ip . ':53389/wsman</a:To>
|
||||
<a:ReplyTo>
|
||||
<a:Address mustUnderstand="true">http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address>
|
||||
</a:ReplyTo>
|
||||
<w:MaxEnvelopeSize mustUnderstand="true">153600</w:MaxEnvelopeSize>
|
||||
<a:MessageID>uuid:' . uniqid() . '</a:MessageID>
|
||||
<w:Locale mustUnderstand="false" xml:lang="en-US"/>
|
||||
<p:DataLocale mustUnderstand="false" xml:lang="en-US"/>
|
||||
<w:OperationTimeout>PT60S</w:OperationTimeout>
|
||||
<w:ResourceURI mustUnderstand="true">http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd</w:ResourceURI>
|
||||
<a:Action mustUnderstand="true">http://schemas.xmlsoap.org/ws/2004/09/transfer/Delete</a:Action>
|
||||
<w:SelectorSet>
|
||||
<w:Selector Name="ShellId">' . $shell_id . '</w:Selector>
|
||||
</w:SelectorSet>
|
||||
</env:Header>
|
||||
<env:Body></env:Body>
|
||||
</env:Envelope>';
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
namespace App\Http\Services;
|
||||
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use App\Http\Services\vCenter\Client;
|
||||
use App\Http\Services\vCenter\PowerManagementService;
|
||||
use App\Http\Services\vCenter\VirtualMachineService;
|
||||
@@ -12,8 +11,6 @@ use App\Http\Services\vCenter\TemplateService;
|
||||
use App\Http\Services\vCenter\VMConfigurationService;
|
||||
use App\Http\Services\vCenter\PowerShellService;
|
||||
use App\Http\Services\vCenter\Concerns\ManagesSsh;
|
||||
use Exception;
|
||||
use phpseclib3\Net\SSH2;
|
||||
|
||||
class vCenter
|
||||
{
|
||||
@@ -26,7 +23,6 @@ class vCenter
|
||||
private int $diskCapacity = 1073741824;
|
||||
private int $memory = 1024;
|
||||
private ?string $os = null;
|
||||
private SSH2|null $process = null;
|
||||
|
||||
private Client $client;
|
||||
private PowerManagementService $power;
|
||||
@@ -339,179 +335,4 @@ class vCenter
|
||||
{
|
||||
return $this->shell->getWindowsRdpPort($vmwareId, $guestUser, $guestPassword);
|
||||
}
|
||||
|
||||
// ─── Legacy VPS Direct SSH ────────────────────────────────────────────────
|
||||
// These methods use direct SSH to guest VM, not via jumphost.
|
||||
|
||||
/** Look up host/user/password for a legacy target from infra_management, decrypting the stored password. */
|
||||
private function resolveLegacyInfra(string $type): ?array
|
||||
{
|
||||
$infra = \App\Models\InfraManagement::where('type', $type)
|
||||
->where('status', true)
|
||||
->first();
|
||||
|
||||
if (!$infra) {
|
||||
Log::error("Legacy VPS lookup failed: no active infra_management row for type={$type}.");
|
||||
return null;
|
||||
}
|
||||
|
||||
return [
|
||||
'ip' => $infra->host,
|
||||
'user' => $infra->username,
|
||||
'password' => \App\Http\Facade\SignRSA::DecryptFunc($infra->password),
|
||||
];
|
||||
}
|
||||
|
||||
protected function loginVPS(array|null $data = []): ?SSH2
|
||||
{
|
||||
try {
|
||||
$ip = $data['ip'] ?? null;
|
||||
$user = $data['user'] ?? null;
|
||||
$password = $data['password'] ?? null;
|
||||
|
||||
if ($ip === null || $user === null || $password === null) {
|
||||
$infra = $this->resolveLegacyInfra('legacy_vps');
|
||||
if (!$infra) {
|
||||
throw new Exception('No legacy VPS credentials available (data not provided and no active infra_management row).');
|
||||
}
|
||||
$ip ??= $infra['ip'];
|
||||
$user ??= $infra['user'];
|
||||
$password ??= $infra['password'];
|
||||
}
|
||||
|
||||
$this->process = new SSH2($ip, 22, 10);
|
||||
if (!$this->process->login($user, $password)) {
|
||||
throw new Exception("Cannot login to VPS with IP: $ip, User: $user");
|
||||
}
|
||||
return $this->process;
|
||||
} catch (Exception $exception) {
|
||||
Log::error('Login VPS failed: ' . $exception->getMessage());
|
||||
$this->process = null;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public function change_password_linux(array $data = ['new_password' => '']): bool
|
||||
{
|
||||
try {
|
||||
if (empty($data['new_password'])) {
|
||||
throw new Exception('New password cannot be empty.');
|
||||
}
|
||||
if (!isset($data['ip'], $data['user'], $data['password'])) {
|
||||
$infra = $this->resolveLegacyInfra('jumphost');
|
||||
if (!$infra) {
|
||||
throw new Exception('No jumphost credentials available in infra_management.');
|
||||
}
|
||||
$data += $infra;
|
||||
}
|
||||
$this->loginVPS($data);
|
||||
if (!$this->process) {
|
||||
throw new Exception('Cannot login to VPS.');
|
||||
}
|
||||
$username = $data['user'] ?? 'root';
|
||||
$newPassword = $data['new_password'];
|
||||
$this->process->exec('echo ' . escapeshellarg("$username:$newPassword") . ' | chpasswd');
|
||||
return true;
|
||||
} catch (Exception $exception) {
|
||||
Log::error('Failed to change password: ' . $exception->getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public function change_password_windows(array $data = ['new_password' => '']): bool
|
||||
{
|
||||
try {
|
||||
if (empty($data['new_password'])) {
|
||||
throw new Exception('New password cannot be empty.');
|
||||
}
|
||||
if (!isset($data['ip'], $data['user'], $data['password'])) {
|
||||
$infra = $this->resolveLegacyInfra('legacy_vps');
|
||||
if (!$infra) {
|
||||
throw new Exception('No legacy VPS credentials available in infra_management.');
|
||||
}
|
||||
$data += $infra;
|
||||
}
|
||||
$this->loginVPS($data);
|
||||
if (!$this->process) {
|
||||
throw new Exception('Cannot login to VPS.');
|
||||
}
|
||||
$username = $data['user'] ?? 'administrator';
|
||||
$newPassword = $data['new_password'];
|
||||
$response = $this->process->exec("net user \"$username\" \"$newPassword\"");
|
||||
if (stripos($response, 'successfully') === false) {
|
||||
throw new Exception("Failed to change password. Response: $response");
|
||||
}
|
||||
return true;
|
||||
} catch (Exception $exception) {
|
||||
Log::error('Failed to change password: ' . $exception->getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public function extend_disk_centos_7(): bool
|
||||
{
|
||||
try {
|
||||
$this->loginVPS();
|
||||
if (!$this->process) {
|
||||
throw new Exception('Cannot login to VPS');
|
||||
}
|
||||
$checkDisk = $this->process->exec("lsblk | grep -w 'sda2'");
|
||||
if (empty(trim($checkDisk))) {
|
||||
throw new Exception('Disk /dev/sda2 not found');
|
||||
}
|
||||
$this->process->exec('sudo tee /sys/class/block/sda/device/rescan');
|
||||
$this->process->exec('sudo pvcreate /dev/sda2');
|
||||
$this->process->exec('sudo vgextend /dev/centos /dev/sda2');
|
||||
$this->process->exec('sudo lvextend /dev/centos/root /dev/sda2');
|
||||
$this->process->exec('sudo xfs_growfs /dev/centos/root');
|
||||
return true;
|
||||
} catch (Exception $exception) {
|
||||
Log::error('Failed to extend disk: ' . $exception->getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public function extend_disk_centos_8(): bool
|
||||
{
|
||||
try {
|
||||
$this->loginVPS();
|
||||
if (!$this->process) {
|
||||
throw new Exception('Cannot login to VPS');
|
||||
}
|
||||
$checkDisk = $this->process->exec("lsblk | grep -w 'sda3'");
|
||||
if (empty(trim($checkDisk))) {
|
||||
throw new Exception('Disk /dev/sda3 not found');
|
||||
}
|
||||
$this->process->exec('sudo pvcreate /dev/sda3');
|
||||
$this->process->exec('sudo vgextend /dev/cl /dev/sda3');
|
||||
$this->process->exec('sudo lvextend /dev/cl/root /dev/sd3');
|
||||
$this->process->exec('sudo xfs_growfs /dev/cl/root');
|
||||
return true;
|
||||
} catch (Exception $exception) {
|
||||
Log::error('Failed to extend disk: ' . $exception->getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public function extend_disk_ubuntu(): bool
|
||||
{
|
||||
try {
|
||||
$this->loginVPS();
|
||||
if (!$this->process) {
|
||||
throw new Exception('Cannot login to VPS');
|
||||
}
|
||||
$checkDisk = $this->process->exec("lsblk | grep -w 'sda3'");
|
||||
if (empty(trim($checkDisk))) {
|
||||
throw new Exception('Disk /dev/sda3 not found');
|
||||
}
|
||||
$this->process->exec('sudo tee /sys/class/block/sda/device/rescan');
|
||||
$this->process->exec('sudo growpart /dev/sda 3');
|
||||
$this->process->exec('sudo pvresize /dev/sda3');
|
||||
$this->process->exec('sudo lvresize -l+100%FREE --resizefs /dev/mapper/ubuntu--vg-ubuntu--lv');
|
||||
return true;
|
||||
} catch (Exception $exception) {
|
||||
Log::error('Failed to extend disk: ' . $exception->getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Http\Services\vCenter;
|
||||
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use App\Support\TlsHttpClientFactory;
|
||||
use App\Http\Facade\SignRSA;
|
||||
use App\Models\Vcenter;
|
||||
use Exception;
|
||||
@@ -23,7 +24,7 @@ class Client
|
||||
$this->username = $vcenterModel->user;
|
||||
$this->password = SignRSA::DecryptFunc($vcenterModel->password);
|
||||
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withBasicAuth($this->username, $this->password)
|
||||
->post("https://{$this->apiUri}/rest/com/vmware/cis/session", []);
|
||||
|
||||
@@ -48,7 +49,7 @@ class Client
|
||||
|
||||
public function checkApiExits(): bool
|
||||
{
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->token
|
||||
])
|
||||
|
||||
@@ -4,6 +4,9 @@ namespace App\Http\Services\vCenter\Concerns;
|
||||
|
||||
use App\Http\Facade\SignRSA;
|
||||
use App\Models\InfraManagement;
|
||||
use App\Support\PowerCliCertificatePolicy;
|
||||
use App\Support\PowerShellEscaper;
|
||||
use App\Support\SshHostKeyVerifier;
|
||||
use Exception;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use phpseclib3\Net\SSH2;
|
||||
@@ -19,6 +22,11 @@ use phpseclib3\Net\SSH2;
|
||||
*/
|
||||
trait ManagesSsh
|
||||
{
|
||||
private function powerCliCertificateLine(): string
|
||||
{
|
||||
return PowerCliCertificatePolicy::configurationLine();
|
||||
}
|
||||
|
||||
// ─── Auth ────────────────────────────────────────────────────────────────
|
||||
|
||||
private function LoginAuth(): SSH2|false
|
||||
@@ -41,6 +49,8 @@ trait ManagesSsh
|
||||
|
||||
$connection = new SSH2($sshHost, $sshPort);
|
||||
|
||||
SshHostKeyVerifier::verify($connection, $sshHost);
|
||||
|
||||
if ($connection->login($infra->username, SignRSA::DecryptFunc($infra->password))) {
|
||||
$connection->setTimeout(0);
|
||||
return $connection;
|
||||
@@ -83,7 +93,7 @@ trait ManagesSsh
|
||||
try {
|
||||
$psCommand = 'powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "'
|
||||
. 'Import-Module VMware.PowerCLI; '
|
||||
. 'Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false -Scope Session; '
|
||||
. $this->powerCliCertificateLine() . '; '
|
||||
. '$cred = Import-Clixml -Path \'C:\secure\vcenter.cred\'; '
|
||||
. 'Connect-VIServer -Server \'' . $this->apiUri . '\' -Credential $cred; '
|
||||
. $cmd . '; '
|
||||
@@ -113,8 +123,8 @@ trait ManagesSsh
|
||||
return 'Login_Fail';
|
||||
}
|
||||
|
||||
$action = 'powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass '
|
||||
. '-Command "' . str_replace('"', '\"', $psCommand) . '"';
|
||||
$action = 'powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand '
|
||||
. PowerShellEscaper::encodedCommand($psCommand);
|
||||
|
||||
try {
|
||||
$out = $auth->exec($action);
|
||||
@@ -136,7 +146,6 @@ trait ManagesSsh
|
||||
return 'Login_Fail';
|
||||
}
|
||||
|
||||
$esc = fn(string $v) => str_replace("'", "''", $v);
|
||||
$script = strtr(
|
||||
<<<'PS'
|
||||
$ProgressPreference = 'SilentlyContinue'
|
||||
@@ -145,7 +154,7 @@ $WarningPreference = 'SilentlyContinue'
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
Import-Module VMware.PowerCLI -ErrorAction Stop
|
||||
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Scope Session -Confirm:$false | Out-Null
|
||||
<CERT>
|
||||
Connect-VIServer -Server '<SERVER>' -User '<USER>' -Password '<PASS>' | Out-Null
|
||||
|
||||
& {
|
||||
@@ -153,15 +162,16 @@ Connect-VIServer -Server '<SERVER>' -User '<USER>' -Password '<PASS>' | Out-Null
|
||||
} | Out-String
|
||||
PS,
|
||||
[
|
||||
'<SERVER>' => $esc($this->apiUri ?? ''),
|
||||
'<USER>' => $esc($this->username ?? ''),
|
||||
'<PASS>' => $esc($this->password ?? ''),
|
||||
'<CERT>' => $this->powerCliCertificateLine(),
|
||||
'<SERVER>' => PowerShellEscaper::singleQuote($this->apiUri ?? ''),
|
||||
'<USER>' => PowerShellEscaper::singleQuote($this->username ?? ''),
|
||||
'<PASS>' => PowerShellEscaper::singleQuote($this->password ?? ''),
|
||||
'<CMD>' => $cmd,
|
||||
]
|
||||
);
|
||||
|
||||
$encoded = base64_encode(mb_convert_encoding($script, 'UTF-16LE', 'UTF-8'));
|
||||
$action = "powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand $encoded";
|
||||
$action = 'powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand '
|
||||
. PowerShellEscaper::encodedCommand($script);
|
||||
|
||||
try {
|
||||
$out = $auth->exec($action);
|
||||
@@ -183,7 +193,6 @@ PS,
|
||||
return 'Login_Fail';
|
||||
}
|
||||
|
||||
$esc = fn(string $v) => str_replace("'", "''", $v);
|
||||
$script = strtr(
|
||||
<<<'PS'
|
||||
$ProgressPreference = 'SilentlyContinue'
|
||||
@@ -193,7 +202,7 @@ $ErrorActionPreference = 'Stop'
|
||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||
|
||||
Import-Module VMware.PowerCLI -ErrorAction Stop
|
||||
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Scope Session -Confirm:$false | Out-Null
|
||||
<CERT>
|
||||
Connect-VIServer -Server '<SERVER>' -User '<USER>' -Password '<PASS>' | Out-Null
|
||||
|
||||
& {
|
||||
@@ -201,15 +210,16 @@ Connect-VIServer -Server '<SERVER>' -User '<USER>' -Password '<PASS>' | Out-Null
|
||||
}
|
||||
PS,
|
||||
[
|
||||
'<SERVER>' => $esc($this->apiUri ?? ''),
|
||||
'<USER>' => $esc($this->username ?? ''),
|
||||
'<PASS>' => $esc($this->password ?? ''),
|
||||
'<CERT>' => $this->powerCliCertificateLine(),
|
||||
'<SERVER>' => PowerShellEscaper::singleQuote($this->apiUri ?? ''),
|
||||
'<USER>' => PowerShellEscaper::singleQuote($this->username ?? ''),
|
||||
'<PASS>' => PowerShellEscaper::singleQuote($this->password ?? ''),
|
||||
'<CMD>' => $cmd,
|
||||
]
|
||||
);
|
||||
|
||||
$encoded = base64_encode(mb_convert_encoding($script, 'UTF-16LE', 'UTF-8'));
|
||||
$action = "powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand $encoded";
|
||||
$action = 'powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand '
|
||||
. PowerShellEscaper::encodedCommand($script);
|
||||
|
||||
try {
|
||||
$out = $auth->exec($action);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Http\Services\vCenter;
|
||||
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use App\Support\TlsHttpClientFactory;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class PowerManagementService
|
||||
@@ -17,7 +18,7 @@ class PowerManagementService
|
||||
public function SuspendVirtualMachine($vmware_id = ''): array|string
|
||||
{
|
||||
if ($this->client->checkApiExits()) {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -39,7 +40,7 @@ class PowerManagementService
|
||||
public function RebootVirtualMachine($product, $vmware_id = ''): array|string
|
||||
{
|
||||
if ($this->client->loginServer($product->ipaddress->host->datacenter->vCenter)) {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -61,7 +62,7 @@ class PowerManagementService
|
||||
public function StartVirtualMachine($product, $vmware_id = ''): array|string
|
||||
{
|
||||
if ($this->client->loginServer($product->ipaddress->host->datacenter->vCenter)) {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -83,7 +84,7 @@ class PowerManagementService
|
||||
public function ShutdownGuestVirtualMachine($product, $vmware_id = ''): array|string
|
||||
{
|
||||
if ($this->client->loginServer($product->ipaddress->host->datacenter->vCenter)) {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -106,7 +107,7 @@ class PowerManagementService
|
||||
public function PowerOffVirtualMachine($vmware_id = ''): array|string
|
||||
{
|
||||
if ($this->client->checkApiExits()) {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -128,7 +129,7 @@ class PowerManagementService
|
||||
public function DeleteVirtualMachine($vmware_id = ''): array|string
|
||||
{
|
||||
if ($this->client->checkApiExits()) {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -150,7 +151,7 @@ class PowerManagementService
|
||||
public function GetConsoleTickets($vmware_id = ''): array|string
|
||||
{
|
||||
if ($this->client->checkApiExits()) {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -219,7 +220,7 @@ class PowerManagementService
|
||||
return "Login_Again";
|
||||
}
|
||||
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -265,7 +266,7 @@ class PowerManagementService
|
||||
return 'Login_Again';
|
||||
}
|
||||
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders(['vmware-api-session-id' => $this->client->token])
|
||||
->timeout(8)
|
||||
->get("https://{$this->client->apiUri}/rest/vcenter/vm/$vmId/power");
|
||||
|
||||
@@ -7,6 +7,9 @@ use phpseclib3\Net\SSH2;
|
||||
use Exception;
|
||||
use App\Models\InfraManagement;
|
||||
use App\Http\Facade\SignRSA;
|
||||
use App\Support\PowerShellEscaper;
|
||||
use App\Support\PowerCliCertificatePolicy;
|
||||
use App\Support\SshHostKeyVerifier;
|
||||
|
||||
class PowerShellService
|
||||
{
|
||||
@@ -41,6 +44,8 @@ class PowerShellService
|
||||
|
||||
$connection = new SSH2($sshHost, $sshPort);
|
||||
|
||||
SshHostKeyVerifier::verify($connection, $sshHost);
|
||||
|
||||
if ($connection->login($sshUser, $sshPass)) {
|
||||
$connection->setTimeout(0); // No timeout
|
||||
return $connection;
|
||||
@@ -72,9 +77,8 @@ class PowerShellService
|
||||
return "Login_Fail";
|
||||
}
|
||||
|
||||
// Action wrapper
|
||||
$action = 'powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass '
|
||||
. '-Command "' . str_replace('"', '\"', $psCommand) . '"';
|
||||
$action = 'powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand '
|
||||
. PowerShellEscaper::encodedCommand($psCommand);
|
||||
|
||||
try {
|
||||
$out = $auth->exec($action);
|
||||
@@ -91,6 +95,11 @@ class PowerShellService
|
||||
return $this->CommandRSP($cmd);
|
||||
}
|
||||
|
||||
private function powerCliCertificateLine(): string
|
||||
{
|
||||
return PowerCliCertificatePolicy::configurationLine();
|
||||
}
|
||||
|
||||
protected function CommandRSP(string $cmd)
|
||||
{
|
||||
$auth = $this->LoginAuth();
|
||||
@@ -98,12 +107,9 @@ class PowerShellService
|
||||
return "Login_Fail";
|
||||
}
|
||||
|
||||
$esc = fn(string $v) => str_replace("'", "''", $v);
|
||||
|
||||
// Get credentials from Client
|
||||
$server = $esc($this->client->apiUri ?? '');
|
||||
$user = $esc($this->client->getUsername() ?? '');
|
||||
$pass = $esc($this->client->getPassword() ?? '');
|
||||
$server = PowerShellEscaper::singleQuote($this->client->apiUri ?? '');
|
||||
$user = PowerShellEscaper::singleQuote($this->client->getUsername() ?? '');
|
||||
$pass = PowerShellEscaper::singleQuote($this->client->getPassword() ?? '');
|
||||
|
||||
$psTemplate = <<<'PS'
|
||||
$ProgressPreference = 'SilentlyContinue'
|
||||
@@ -112,7 +118,7 @@ $WarningPreference = 'SilentlyContinue'
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
Import-Module VMware.PowerCLI -ErrorAction Stop
|
||||
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Scope Session -Confirm:$false | Out-Null
|
||||
<CERT>
|
||||
Connect-VIServer -Server '<SERVER>' -User '<USER>' -Password '<PASS>' | Out-Null
|
||||
|
||||
& {
|
||||
@@ -121,19 +127,19 @@ Connect-VIServer -Server '<SERVER>' -User '<USER>' -Password '<PASS>' | Out-Null
|
||||
PS;
|
||||
|
||||
$psScript = strtr($psTemplate, [
|
||||
'<CERT>' => $this->powerCliCertificateLine(),
|
||||
'<SERVER>' => $server,
|
||||
'<USER>' => $user,
|
||||
'<PASS>' => $pass,
|
||||
'<CMD>' => $cmd,
|
||||
]);
|
||||
|
||||
$encoded = base64_encode(mb_convert_encoding($psScript, 'UTF-16LE', 'UTF-8'));
|
||||
$action = "powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand $encoded";
|
||||
$action = 'powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand '
|
||||
. PowerShellEscaper::encodedCommand($psScript);
|
||||
|
||||
try {
|
||||
$out = $auth->exec($action);
|
||||
$errOut = $auth->getStdError();
|
||||
// PowerCLI banner is CLIXML informational records — not an error
|
||||
$realErr = $errOut && !str_starts_with(trim($errOut), '#< CLIXML');
|
||||
return $out . ($realErr ? "\n[STDERR]\n" . $errOut : '');
|
||||
} catch (\Throwable $e) {
|
||||
@@ -148,11 +154,9 @@ PS;
|
||||
return "Login_Fail";
|
||||
}
|
||||
|
||||
$esc = fn(string $v) => str_replace("'", "''", $v);
|
||||
|
||||
$server = $esc($this->client->apiUri ?? '');
|
||||
$user = $esc($this->client->getUsername() ?? '');
|
||||
$pass = $esc($this->client->getPassword() ?? '');
|
||||
$server = PowerShellEscaper::singleQuote($this->client->apiUri ?? '');
|
||||
$user = PowerShellEscaper::singleQuote($this->client->getUsername() ?? '');
|
||||
$pass = PowerShellEscaper::singleQuote($this->client->getPassword() ?? '');
|
||||
|
||||
$psTemplate = <<<'PS'
|
||||
$ProgressPreference = 'SilentlyContinue'
|
||||
@@ -162,7 +166,7 @@ $ErrorActionPreference = 'Stop'
|
||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||
|
||||
Import-Module VMware.PowerCLI -ErrorAction Stop
|
||||
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Scope Session -Confirm:$false | Out-Null
|
||||
<CERT>
|
||||
Connect-VIServer -Server '<SERVER>' -User '<USER>' -Password '<PASS>' | Out-Null
|
||||
|
||||
& {
|
||||
@@ -171,14 +175,15 @@ Connect-VIServer -Server '<SERVER>' -User '<USER>' -Password '<PASS>' | Out-Null
|
||||
PS;
|
||||
|
||||
$psScript = strtr($psTemplate, [
|
||||
'<CERT>' => $this->powerCliCertificateLine(),
|
||||
'<SERVER>' => $server,
|
||||
'<USER>' => $user,
|
||||
'<PASS>' => $pass,
|
||||
'<CMD>' => $cmd,
|
||||
]);
|
||||
|
||||
$encoded = base64_encode(mb_convert_encoding($psScript, 'UTF-16LE', 'UTF-8'));
|
||||
$action = "powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand $encoded";
|
||||
$action = 'powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand '
|
||||
. PowerShellEscaper::encodedCommand($psScript);
|
||||
|
||||
try {
|
||||
$out = $auth->exec($action);
|
||||
@@ -201,15 +206,14 @@ PS;
|
||||
public function resetGuestPasswordViaPs1(string $vmName, string $guestUser, string $guestPassword, string $newPassword, string $targetUser = 'Administrator'): array|string
|
||||
{
|
||||
$psFile = "C:\\CLISave\\AssignIP\\SetGuestPwd.ps1";
|
||||
$q = fn(string $v) => str_replace("'", "''", $v);
|
||||
|
||||
$args = " -VMName '" . $q($vmName) . "'";
|
||||
$args .= " -GuestUser '" . $q($guestUser) . "'";
|
||||
$args .= " -GuestPassword '" . $q($guestPassword) . "'";
|
||||
$args .= " -TargetUser '" . $q($targetUser) . "'";
|
||||
$args .= " -NewPassword '" . $q($newPassword) . "'";
|
||||
$args = ' -VMName ' . PowerShellEscaper::singleQuote($vmName);
|
||||
$args .= ' -GuestUser ' . PowerShellEscaper::singleQuote($guestUser);
|
||||
$args .= ' -GuestPassword ' . PowerShellEscaper::singleQuote($guestPassword);
|
||||
$args .= ' -TargetUser ' . PowerShellEscaper::singleQuote($targetUser);
|
||||
$args .= ' -NewPassword ' . PowerShellEscaper::singleQuote($newPassword);
|
||||
|
||||
$cmd = "& '$psFile'$args | Out-String";
|
||||
$cmd = '& ' . PowerShellEscaper::singleQuote($psFile) . "{$args} | Out-String";
|
||||
|
||||
$raw = $this->CommandRSP($cmd);
|
||||
if ($raw === 'Login_Fail' || $raw === false || $raw === null) {
|
||||
@@ -230,14 +234,13 @@ PS;
|
||||
public function changeRDPPortWindows(string $vmName, string $guestUser, string $guestPassword, string $newPort): array|string
|
||||
{
|
||||
$psFile = "C:\\CLISave\\AssignIP\\change-rdp-port.ps1";
|
||||
$q = fn(string $v) => str_replace("'", "''", $v);
|
||||
|
||||
$args = " -VMName '" . $q($vmName) . "'";
|
||||
$args .= " -GuestUser '" . $q($guestUser) . "'";
|
||||
$args .= " -GuestPassword '" . $q($guestPassword) . "'";
|
||||
$args .= " -NewPort " . (int) $newPort;
|
||||
$args = ' -VMName ' . PowerShellEscaper::singleQuote($vmName);
|
||||
$args .= ' -GuestUser ' . PowerShellEscaper::singleQuote($guestUser);
|
||||
$args .= ' -GuestPassword ' . PowerShellEscaper::singleQuote($guestPassword);
|
||||
$args .= ' -NewPort ' . (int) $newPort;
|
||||
|
||||
$cmd = "& '$psFile'$args";
|
||||
$cmd = '& ' . PowerShellEscaper::singleQuote($psFile) . $args;
|
||||
|
||||
$raw = $this->CommandChangePort($cmd, true);
|
||||
|
||||
@@ -286,8 +289,6 @@ PS;
|
||||
string $dns = '8.8.8.8',
|
||||
string $hostname = ''
|
||||
): string {
|
||||
$q = fn(string $v) => str_replace("'", "''", $v);
|
||||
|
||||
$isLinux = str_contains(strtolower($osType), 'linux')
|
||||
|| str_contains(strtolower($osType), 'ubuntu')
|
||||
|| str_contains(strtolower($osType), 'centos')
|
||||
@@ -295,29 +296,35 @@ PS;
|
||||
|
||||
if ($isLinux) {
|
||||
$psFile = "C:\\CLISave\\changeIPLinux.ps1";
|
||||
$Command = "& '{$psFile}'"
|
||||
. " -VMName '" . $q($vmName) . "'"
|
||||
. " -IP '" . $q($ipAddress) . "'"
|
||||
. " -Gateway '" . $q($gateway) . "'"
|
||||
. " -DNS '" . $q($dns) . "'"
|
||||
. " -GuestUser '" . $q($guestUser) . "'"
|
||||
. " -GuestPassword '" . $q($guestPassword) . "'";
|
||||
$Command = '& ' . PowerShellEscaper::singleQuote($psFile)
|
||||
. ' -VMName ' . PowerShellEscaper::singleQuote($vmName)
|
||||
. ' -IP ' . PowerShellEscaper::singleQuote($ipAddress)
|
||||
. ' -Gateway ' . PowerShellEscaper::singleQuote($gateway)
|
||||
. ' -DNS ' . PowerShellEscaper::singleQuote($dns)
|
||||
. ' -GuestUser ' . PowerShellEscaper::singleQuote($guestUser)
|
||||
. ' -GuestPassword ' . PowerShellEscaper::singleQuote($guestPassword);
|
||||
|
||||
Log::channel('Custom')->info('[changeIpVM:linux] ' . $Command);
|
||||
Log::channel('Custom')->info('[changeIpVM:linux]', [
|
||||
'script' => 'changeIPLinux.ps1',
|
||||
'vmware_id' => $vmwareId,
|
||||
]);
|
||||
|
||||
return (string) $this->CommandChangePort($Command, true);
|
||||
}
|
||||
|
||||
$VirtualMachine = "VirtualMachine-$vmwareId";
|
||||
$hn = strtolower($hostname ?: $vmName);
|
||||
$Command = "\$vm = get-vm -Id '{$VirtualMachine}';"
|
||||
. " \$hostname = '{$q($hn)}';"
|
||||
. " \$ipadd = '{$q($ipAddress)}';"
|
||||
. " \$gw = '{$q($gateway)}';"
|
||||
. " \$password = \"'{$q($guestPassword)}'\"; "
|
||||
. " cd /; C:\\CLISave\\changeWindows1line.ps1;";
|
||||
$Command = '$vm = get-vm -Id ' . PowerShellEscaper::singleQuote($VirtualMachine) . ';'
|
||||
. ' $hostname = ' . PowerShellEscaper::singleQuote($hn) . ';'
|
||||
. ' $ipadd = ' . PowerShellEscaper::singleQuote($ipAddress) . ';'
|
||||
. ' $gw = ' . PowerShellEscaper::singleQuote($gateway) . ';'
|
||||
. ' $password = ' . PowerShellEscaper::singleQuote($guestPassword) . '; '
|
||||
. ' cd /; C:\\CLISave\\changeWindows1line.ps1;';
|
||||
|
||||
Log::channel('Custom')->info('[changeIpVM:windows] ' . $Command);
|
||||
Log::channel('Custom')->info('[changeIpVM:windows]', [
|
||||
'script' => 'changeWindows1line.ps1',
|
||||
'vmware_id' => $vmwareId,
|
||||
]);
|
||||
|
||||
return (string) $this->CommandRSP($Command);
|
||||
}
|
||||
@@ -326,11 +333,11 @@ PS;
|
||||
{
|
||||
$ps = "(Get-ItemProperty 'HKLM:\\System\\CurrentControlSet\\Control\\Terminal Server\\WinStations\\RDP-Tcp' -Name PortNumber).PortNumber";
|
||||
|
||||
$cmd = "Invoke-VMScript -VM '$vmwareId' "
|
||||
. "-ScriptText \"$ps\" "
|
||||
. "-ScriptType Powershell "
|
||||
. "-GuestUser '$guestUser' "
|
||||
. "-GuestPassword '$guestPassword'";
|
||||
$cmd = 'Invoke-VMScript -VM ' . PowerShellEscaper::singleQuote($vmwareId)
|
||||
. ' -ScriptText ' . PowerShellEscaper::singleQuote($ps)
|
||||
. ' -ScriptType Powershell'
|
||||
. ' -GuestUser ' . PowerShellEscaper::singleQuote($guestUser)
|
||||
. ' -GuestPassword ' . PowerShellEscaper::singleQuote($guestPassword);
|
||||
|
||||
$output = $this->CommandRSP($cmd);
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Http\Services\vCenter;
|
||||
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use App\Support\TlsHttpClientFactory;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class ResourceService
|
||||
@@ -17,7 +18,7 @@ class ResourceService
|
||||
public function getAllDatacenter()
|
||||
{
|
||||
if ($this->client->checkApiExits()) {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -34,7 +35,7 @@ class ResourceService
|
||||
public function getAllHost($datacenter = '')
|
||||
{
|
||||
if ($this->client->checkApiExits()) {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -53,7 +54,7 @@ class ResourceService
|
||||
public function getAllFolder($datacenter = '')
|
||||
{
|
||||
if ($this->client->checkApiExits()) {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -80,7 +81,7 @@ class ResourceService
|
||||
$params['filter.datacenters'] = $datacenter;
|
||||
}
|
||||
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -115,7 +116,7 @@ class ResourceService
|
||||
$params['filter.datacenters'] = $datacenter;
|
||||
}
|
||||
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -171,7 +172,7 @@ class ResourceService
|
||||
$params['filter.datacenters'] = $datacenter;
|
||||
}
|
||||
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Http\Services\vCenter;
|
||||
|
||||
use App\Support\Cache\CacheKey;
|
||||
use App\Support\TlsHttpClientFactory;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
@@ -438,7 +439,7 @@ class SnapshotService
|
||||
' . $soapBody . '
|
||||
</soapenv:Envelope>';
|
||||
|
||||
curl_setopt_array($curl, array(
|
||||
curl_setopt_array($curl, [
|
||||
CURLOPT_URL => "https://$host/sdk",
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_ENCODING => '',
|
||||
@@ -449,10 +450,8 @@ class SnapshotService
|
||||
CURLOPT_CUSTOMREQUEST => 'POST',
|
||||
CURLOPT_POSTFIELDS => $payload,
|
||||
CURLOPT_HTTPHEADER => $headers,
|
||||
CURLOPT_SSL_VERIFYHOST => false,
|
||||
CURLOPT_SSL_VERIFYPEER => false,
|
||||
CURLOPT_HEADER => true // We need headers for cookie
|
||||
));
|
||||
] + TlsHttpClientFactory::vCenterCurlOptions());
|
||||
|
||||
$response = curl_exec($curl);
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Http\Services\vCenter;
|
||||
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use App\Support\TlsHttpClientFactory;
|
||||
|
||||
class TemplateService
|
||||
{
|
||||
@@ -16,7 +17,7 @@ class TemplateService
|
||||
public function getAllTemplate()
|
||||
{
|
||||
if ($this->client->checkApiExits()) {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -32,7 +33,7 @@ class TemplateService
|
||||
|
||||
public function getTemplatebyID($template = '')
|
||||
{
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -61,7 +62,7 @@ class TemplateService
|
||||
|
||||
public function getVersionDetail($version_id = '')
|
||||
{
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -76,7 +77,7 @@ class TemplateService
|
||||
public function getAllVersion($library = ''): bool|array|string
|
||||
{
|
||||
if ($this->client->checkApiExits()) {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Http\Services\vCenter;
|
||||
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use App\Support\TlsHttpClientFactory;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Support\Str;
|
||||
@@ -32,7 +33,7 @@ class VirtualMachineService
|
||||
$params['filter.hosts'] = $host;
|
||||
}
|
||||
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -111,7 +112,7 @@ class VirtualMachineService
|
||||
try {
|
||||
Log::info('Bắt đầu clone VM với timeout 300 giây', ['template' => $template, 'target_name' => $body['spec']['name']]);
|
||||
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->timeout(300)
|
||||
->connectTimeout(30)
|
||||
->withHeaders([
|
||||
@@ -230,7 +231,7 @@ class VirtualMachineService
|
||||
'hot_add_enabled' => true
|
||||
]
|
||||
];
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->timeout(30)
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token,
|
||||
@@ -264,7 +265,7 @@ class VirtualMachineService
|
||||
]
|
||||
];
|
||||
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->timeout(30)
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token,
|
||||
@@ -299,7 +300,7 @@ class VirtualMachineService
|
||||
]
|
||||
];
|
||||
|
||||
$diskResponse = Http::withoutVerifying()
|
||||
$diskResponse = TlsHttpClientFactory::vCenter()
|
||||
->timeout(30)
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token,
|
||||
@@ -318,7 +319,7 @@ class VirtualMachineService
|
||||
$firstDisk = $diskData['value'][0];
|
||||
$diskKey = $firstDisk['key'];
|
||||
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->timeout(30)
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token,
|
||||
@@ -340,7 +341,7 @@ class VirtualMachineService
|
||||
public function CheckVirtualMachine($vmware_id = '')
|
||||
{
|
||||
if ($this->client->checkApiExits()) {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -358,7 +359,7 @@ class VirtualMachineService
|
||||
{
|
||||
$check = $this->client->checkApiExits();
|
||||
if ($check) {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -383,7 +384,7 @@ class VirtualMachineService
|
||||
return null;
|
||||
}
|
||||
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -406,7 +407,7 @@ class VirtualMachineService
|
||||
|
||||
public function GetDetailVirtualMachine($vmware_id = ''): array
|
||||
{
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -425,7 +426,7 @@ class VirtualMachineService
|
||||
|
||||
public function GetIPAddressVirtualMachine($vmware_id = ''): array
|
||||
{
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -451,7 +452,7 @@ class VirtualMachineService
|
||||
];
|
||||
|
||||
try {
|
||||
$hardwareResponse = Http::withoutVerifying()
|
||||
$hardwareResponse = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -480,7 +481,7 @@ class VirtualMachineService
|
||||
}
|
||||
}
|
||||
|
||||
$guestMemoryResponse = Http::withoutVerifying()
|
||||
$guestMemoryResponse = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -494,7 +495,7 @@ class VirtualMachineService
|
||||
: 0;
|
||||
}
|
||||
|
||||
$guestCpuResponse = Http::withoutVerifying()
|
||||
$guestCpuResponse = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -512,7 +513,7 @@ class VirtualMachineService
|
||||
|
||||
public function ConfigNetworkVirtualMachine($vmware_id = '', $config = []): int
|
||||
{
|
||||
return Http::withoutVerifying()
|
||||
return TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -526,7 +527,7 @@ class VirtualMachineService
|
||||
|
||||
if ($check) {
|
||||
try {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -552,7 +553,7 @@ class VirtualMachineService
|
||||
}
|
||||
|
||||
try {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -578,7 +579,7 @@ class VirtualMachineService
|
||||
|
||||
$vmId = $vmList[0]['vm'];
|
||||
|
||||
$detailResponse = Http::withoutVerifying()
|
||||
$detailResponse = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -655,7 +656,7 @@ class VirtualMachineService
|
||||
"size_MiB" => $ram * 1024,
|
||||
]
|
||||
];
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
@@ -686,7 +687,7 @@ class VirtualMachineService
|
||||
"count" => $cpu
|
||||
]
|
||||
];
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders([
|
||||
'vmware-api-session-id' => $this->client->token
|
||||
])
|
||||
|
||||
@@ -16,17 +16,33 @@ class DnsDomainWriter
|
||||
return false;
|
||||
}
|
||||
|
||||
DB::table('dns_manager_domain')->updateOrInsert(
|
||||
['legacy_id' => $data->legacyId],
|
||||
[
|
||||
'domain_name' => $data->domainName,
|
||||
'dns_manager_server_id' => $data->dnsManagerServerId,
|
||||
'is_created' => $data->isCreated,
|
||||
'plesk_id' => $data->pleskId,
|
||||
'created_at' => $data->createdAt,
|
||||
'updated_at' => $data->updatedAt,
|
||||
]
|
||||
);
|
||||
$attributes = [
|
||||
'legacy_id' => $data->legacyId,
|
||||
'domain_name' => $data->domainName,
|
||||
'dns_manager_server_id' => $data->dnsManagerServerId,
|
||||
'is_created' => $data->isCreated,
|
||||
'plesk_id' => $data->pleskId,
|
||||
'created_at' => $data->createdAt,
|
||||
'updated_at' => $data->updatedAt,
|
||||
];
|
||||
|
||||
$existingId = DB::table('dns_manager_domain')->where('legacy_id', $data->legacyId)->value('id');
|
||||
|
||||
// A WHMCS-created placeholder (DnsDomainLinker) has legacy_id NULL and the same
|
||||
// domain_name — adopt it instead of inserting a duplicate row that would strand
|
||||
// dns_domain_user pointing at the empty placeholder while NS records attach here.
|
||||
if (! $existingId && $data->domainName !== null) {
|
||||
$existingId = DB::table('dns_manager_domain')
|
||||
->whereNull('legacy_id')
|
||||
->whereRaw('LOWER(domain_name) = ?', [mb_strtolower($data->domainName)])
|
||||
->value('id');
|
||||
}
|
||||
|
||||
if ($existingId) {
|
||||
DB::table('dns_manager_domain')->where('id', $existingId)->update($attributes);
|
||||
} else {
|
||||
DB::table('dns_manager_domain')->insert($attributes);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ class ProductCategoryData
|
||||
{
|
||||
public function __construct(
|
||||
public readonly int $legacyId,
|
||||
public readonly ?int $adoptId,
|
||||
public readonly string $name,
|
||||
public readonly string $slug,
|
||||
public readonly ?string $type,
|
||||
|
||||
@@ -5,7 +5,6 @@ namespace App\Integrations\Whmcs\Support;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/** Slugifies a candidate and appends -N until it's unique in the given column, excluding the row's own legacy_id. */
|
||||
class SlugUniquifier
|
||||
{
|
||||
public function unique(string $table, string $column, string $candidate, int $legacyId): string
|
||||
@@ -14,10 +13,27 @@ class SlugUniquifier
|
||||
$slug = $base;
|
||||
$suffix = 1;
|
||||
|
||||
while (DB::table($table)->where($column, $slug)->where('legacy_id', '!=', $legacyId)->exists()) {
|
||||
while ($this->ownedByAnotherRow($table, $column, $slug, $legacyId)) {
|
||||
$slug = "{$base}-" . ++$suffix;
|
||||
}
|
||||
|
||||
return $slug;
|
||||
}
|
||||
|
||||
public function adoptableId(string $table, string $column, string $candidate): ?int
|
||||
{
|
||||
$slug = Str::slug($candidate) ?: 'item';
|
||||
|
||||
return DB::table($table)->where($column, $slug)->whereNull('legacy_id')->value('id');
|
||||
}
|
||||
|
||||
private function ownedByAnotherRow(string $table, string $column, string $slug, int $legacyId): bool
|
||||
{
|
||||
return DB::table($table)
|
||||
->where($column, $slug)
|
||||
->where(function ($query) use ($legacyId) {
|
||||
$query->whereNull('legacy_id')->orWhere('legacy_id', '!=', $legacyId);
|
||||
})
|
||||
->exists();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,11 +17,17 @@ class ProductCategoryTransformer
|
||||
$row = (array) $row;
|
||||
$legacyId = (int) $row['id'];
|
||||
$name = $row['name'] ?: "WHMCS Group {$legacyId}";
|
||||
$candidate = $row['slug'] ?: $name;
|
||||
|
||||
$adoptId = $this->slugs->adoptableId('product_categories', 'slug', $candidate);
|
||||
|
||||
return new ProductCategoryData(
|
||||
legacyId: $legacyId,
|
||||
adoptId: $adoptId,
|
||||
name: $name,
|
||||
slug: $this->slugs->unique('product_categories', 'slug', $row['slug'] ?: $name, $legacyId),
|
||||
slug: $adoptId
|
||||
? (Str::slug($candidate) ?: 'item')
|
||||
: $this->slugs->unique('product_categories', 'slug', $candidate, $legacyId),
|
||||
type: $this->guessType($name),
|
||||
isActive: ! $row['hidden'],
|
||||
sortOrder: (int) $row['order'],
|
||||
|
||||
@@ -10,8 +10,9 @@ class ProductCategoryWriter
|
||||
public function write(ProductCategoryData $data): void
|
||||
{
|
||||
DB::table('product_categories')->updateOrInsert(
|
||||
['legacy_id' => $data->legacyId],
|
||||
$data->adoptId ? ['id' => $data->adoptId] : ['legacy_id' => $data->legacyId],
|
||||
[
|
||||
'legacy_id' => $data->legacyId,
|
||||
'name' => $data->name,
|
||||
'slug' => $data->slug,
|
||||
'type' => $data->type,
|
||||
|
||||
@@ -60,7 +60,7 @@ class ExpiryMail implements ShouldQueue
|
||||
'client_name' => $product->Customer->firstname . " " . $product->Customer->lastname,
|
||||
'product_name' => $product->GetInvoiceItem()->GetItemProduct()->name,
|
||||
'service_due_exp' => Carbon::parse($product->next_due_date)->format('d/m/Y'),
|
||||
'service_remaining' => Carbon::now()->diffInDays(Carbon::parse($product->next_due_date),false) + 1
|
||||
'service_remaining' => (int) Carbon::now()->diffInDays(Carbon::parse($product->next_due_date), false) + 1
|
||||
];
|
||||
|
||||
try {
|
||||
|
||||
@@ -7,6 +7,7 @@ namespace App\Jobs\VirtualMachine;
|
||||
use App\Actions\VM\ChangeIpVMAction;
|
||||
use App\Http\Services\Telegram;
|
||||
use App\Models\ModuleVmware;
|
||||
use App\Services\VirtualMachine\VmIpReservationService;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
@@ -38,9 +39,11 @@ class ChangeIpVMJob implements ShouldQueue
|
||||
public readonly string $dns,
|
||||
public readonly string $guestUser,
|
||||
public readonly string $guestPassword,
|
||||
public readonly ?int $newIpPoolId = null,
|
||||
public readonly ?int $oldIpPoolId = null,
|
||||
) {}
|
||||
|
||||
public function handle(ChangeIpVMAction $action): void
|
||||
public function handle(ChangeIpVMAction $action, VmIpReservationService $ipReservation): void
|
||||
{
|
||||
$vm = ModuleVmware::with([
|
||||
'vCenter',
|
||||
@@ -49,6 +52,9 @@ class ChangeIpVMJob implements ShouldQueue
|
||||
|
||||
if (!$vm) {
|
||||
Log::error('[ChangeIpVMJob] ModuleVmware not found', ['module_vmware_id' => $this->moduleVmwareId]);
|
||||
if ($this->newIpPoolId) {
|
||||
$ipReservation->releaseByPoolId($this->newIpPoolId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -62,6 +68,22 @@ class ChangeIpVMJob implements ShouldQueue
|
||||
$this->guestPassword,
|
||||
);
|
||||
|
||||
$failed = $raw === 'Login_Again'
|
||||
|| $raw === 'vCenter_Not_Found'
|
||||
|| str_starts_with((string) $raw, 'Error:')
|
||||
|| str_contains((string) $raw, '[STDERR]');
|
||||
|
||||
if ($failed) {
|
||||
if ($this->newIpPoolId) {
|
||||
$ipReservation->releaseByPoolId($this->newIpPoolId);
|
||||
}
|
||||
} else {
|
||||
$vm->update(['ip' => $this->ipAddress, 'dns' => $this->dns]);
|
||||
if ($this->oldIpPoolId) {
|
||||
$ipReservation->releaseByPoolId($this->oldIpPoolId);
|
||||
}
|
||||
}
|
||||
|
||||
Log::channel('Custom')->info('[ChangeIpVMJob] raw output', [
|
||||
'module_vmware_id' => $this->moduleVmwareId,
|
||||
'ip_address' => $this->ipAddress,
|
||||
@@ -88,7 +110,7 @@ class ChangeIpVMJob implements ShouldQueue
|
||||
return;
|
||||
}
|
||||
|
||||
if (str_starts_with((string) $raw, 'Error:') || str_contains((string) $raw, '[STDERR]')) {
|
||||
if ($failed) {
|
||||
$telegram->SendErrorMessage("❌ Đổi IP thất bại [{$this->osType}]\n"
|
||||
. "🖥 VM: {$vm->name} ({$vm->vmware_id})\n"
|
||||
. "📍 IP mới: {$this->ipAddress}\n"
|
||||
@@ -116,5 +138,9 @@ class ChangeIpVMJob implements ShouldQueue
|
||||
'ip_address' => $this->ipAddress,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
if ($this->newIpPoolId) {
|
||||
app(VmIpReservationService::class)->releaseByPoolId($this->newIpPoolId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,192 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Jobs\VirtualMachine\Create;
|
||||
|
||||
use App\Http\Facade\SignRSA;
|
||||
use App\Jobs\Mail\SendInformationVirtualMachine;
|
||||
use App\Models\ModuleVmware;
|
||||
use App\Models\Setting;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class ChangePasswordViaSshJob implements ShouldQueue
|
||||
{
|
||||
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||
|
||||
public int $tries = 3;
|
||||
public int $backoff = 120;
|
||||
|
||||
public function __construct(
|
||||
public readonly int $moduleVmwareId,
|
||||
public readonly string $ip,
|
||||
public readonly string $username,
|
||||
public readonly string $initialPassword,
|
||||
public readonly string $newPassword,
|
||||
) {}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
public function handle(): void
|
||||
{
|
||||
Log::info('ChangePasswordViaSshJob: starting', [
|
||||
'module_vmware_id' => $this->moduleVmwareId,
|
||||
'ip' => $this->ip,
|
||||
'username' => $this->username,
|
||||
]);
|
||||
|
||||
$output = $this->runWithRetry();
|
||||
|
||||
if ($output === null) {
|
||||
$this->fail(new \RuntimeException(
|
||||
"SSH connection to {$this->ip} failed after max attempts"
|
||||
));
|
||||
return;
|
||||
}
|
||||
|
||||
Log::info('ChangePasswordViaSshJob: chpasswd output', [
|
||||
'module_vmware_id' => $this->moduleVmwareId,
|
||||
'output' => trim($output),
|
||||
]);
|
||||
|
||||
// Update DB
|
||||
$vm = ModuleVmware::find($this->moduleVmwareId);
|
||||
|
||||
if (!$vm) {
|
||||
Log::error('ChangePasswordViaSshJob: ModuleVmware not found', [
|
||||
'module_vmware_id' => $this->moduleVmwareId,
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
$vm->update([
|
||||
'password' => SignRSA::EncryptFunc($this->newPassword),
|
||||
'plain_password' => $this->newPassword,
|
||||
]);
|
||||
|
||||
$this->sendPasswordEmail($vm);
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Run chpasswd on the remote VM via sshpass + native SSH.
|
||||
* Retries up to 10 times with 30 s delay (VM may still be booting).
|
||||
*/
|
||||
private function runWithRetry(int $maxAttempts = 10, int $sleepSeconds = 30): ?string
|
||||
{
|
||||
// Remote bash command: echo 'user:pass' | chpasswd
|
||||
$credential = $this->username . ':' . $this->newPassword;
|
||||
$remoteCmd = 'echo ' . escapeshellarg($credential) . ' | chpasswd 2>&1';
|
||||
|
||||
$sshCmd = sprintf(
|
||||
'sshpass -p %s ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 -p 22 %s@%s %s 2>&1',
|
||||
escapeshellarg($this->initialPassword),
|
||||
escapeshellarg($this->username),
|
||||
escapeshellarg($this->ip),
|
||||
escapeshellarg($remoteCmd),
|
||||
);
|
||||
|
||||
for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) {
|
||||
$output = shell_exec($sshCmd);
|
||||
|
||||
// null = shell_exec failed (command not found, etc.)
|
||||
// sshpass exits non-zero on connection failure → output contains error text
|
||||
if ($output !== null && !$this->isSshConnectionError($output)) {
|
||||
Log::info('ChangePasswordViaSshJob: SSH connected', [
|
||||
'module_vmware_id' => $this->moduleVmwareId,
|
||||
'attempt' => $attempt,
|
||||
]);
|
||||
return $output;
|
||||
}
|
||||
|
||||
Log::warning('ChangePasswordViaSshJob: SSH not ready, retrying', [
|
||||
'module_vmware_id' => $this->moduleVmwareId,
|
||||
'attempt' => $attempt,
|
||||
'output_preview' => substr((string) $output, 0, 200),
|
||||
]);
|
||||
|
||||
if ($attempt < $maxAttempts) {
|
||||
sleep($sleepSeconds);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect SSH connection failures (not auth errors) in sshpass output.
|
||||
*/
|
||||
private function isSshConnectionError(string $output): bool
|
||||
{
|
||||
$lower = strtolower($output);
|
||||
|
||||
return str_contains($lower, 'connection refused')
|
||||
|| str_contains($lower, 'no route to host')
|
||||
|| str_contains($lower, 'connection timed out')
|
||||
|| str_contains($lower, 'host is down')
|
||||
|| str_contains($lower, 'network is unreachable');
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
public function failed(\Throwable $e): void
|
||||
{
|
||||
Log::error('ChangePasswordViaSshJob: failed', [
|
||||
'module_vmware_id' => $this->moduleVmwareId,
|
||||
'ip' => $this->ip,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
private function sendPasswordEmail(ModuleVmware $vm): void
|
||||
{
|
||||
try {
|
||||
$customer = $vm->customer;
|
||||
|
||||
if (!$customer) {
|
||||
Log::error('ChangePasswordViaSshJob: customer not found', [
|
||||
'module_vmware_id' => $this->moduleVmwareId,
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
$setting = Setting::where('key', 'setting')->first();
|
||||
$settingValue = $setting ? json_decode((string) $setting->value) : null;
|
||||
|
||||
$emailData = [
|
||||
'company_name' => $settingValue->company ?? 'Thế Giới Số',
|
||||
'company_logo' => $settingValue->logo ?? '',
|
||||
'client_name' => trim($customer->firstname . ' ' . $customer->lastname),
|
||||
'product_name' => 'Cloud VPS',
|
||||
'product_billing' => 'N/A',
|
||||
'product_price' => 'N/A',
|
||||
'service_host' => $this->ip,
|
||||
'service_username' => $this->username,
|
||||
'service_port' => 22,
|
||||
'service_password' => $this->newPassword,
|
||||
'os_name' => ($vm->os?->osGroup?->name ?? '') . ' ' . ($vm->os?->version ?? ''),
|
||||
'service_due_exp' => $vm->next_due_date ? date('d/m/Y', (int) $vm->next_due_date) : 'N/A',
|
||||
];
|
||||
|
||||
SendInformationVirtualMachine::dispatch($emailData, $customer)
|
||||
->delay(now()->addSeconds(5));
|
||||
|
||||
Log::info('ChangePasswordViaSshJob: email dispatched', [
|
||||
'module_vmware_id' => $this->moduleVmwareId,
|
||||
'customer_email' => $customer->email,
|
||||
]);
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('ChangePasswordViaSshJob: email failed: ' . $e->getMessage(), [
|
||||
'module_vmware_id' => $this->moduleVmwareId,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@ use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use App\Support\TlsHttpClientFactory;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
@@ -309,14 +309,14 @@ class UpdateVmConfigJob implements ShouldQueue
|
||||
$action = $powerOff ? 'stop' : 'start';
|
||||
$targetState = $powerOff ? 'POWERED_OFF' : 'POWERED_ON';
|
||||
|
||||
Http::withoutVerifying()
|
||||
TlsHttpClientFactory::vCenter()
|
||||
->withHeaders(['vmware-api-session-id' => $service->token])
|
||||
->post("https://{$service->apiUri}/rest/vcenter/vm/{$vmwareId}/power/{$action}");
|
||||
|
||||
for ($i = 0; $i < 15; $i++) {
|
||||
sleep(2);
|
||||
|
||||
$state = Http::withoutVerifying()
|
||||
$state = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders(['vmware-api-session-id' => $service->token])
|
||||
->get("https://{$service->apiUri}/rest/vcenter/vm/{$vmwareId}")
|
||||
->json('value.power_state');
|
||||
|
||||
@@ -43,6 +43,13 @@ class DomainPricing extends Model
|
||||
return is_numeric($value) ? (int) $value : (string) $value;
|
||||
}
|
||||
|
||||
public function orderPrice(int $years): int
|
||||
{
|
||||
$setupFee = is_numeric($this->setup_fee) ? (int) $this->setup_fee : 0;
|
||||
|
||||
return $setupFee + (int) $this->first_year + (int) $this->recurring_fee * (max(1, $years) - 1);
|
||||
}
|
||||
|
||||
public function toDomainArray(): array
|
||||
{
|
||||
return [
|
||||
|
||||
@@ -52,6 +52,12 @@ class Invoice extends Model
|
||||
return $this->hasMany(Service::class, 'invoice_id');
|
||||
}
|
||||
|
||||
/** The service this invoice upgrades, for invoice_type = 3 (upgrade). */
|
||||
public function service()
|
||||
{
|
||||
return $this->belongsTo(Service::class, 'service_id');
|
||||
}
|
||||
|
||||
|
||||
public function payment()
|
||||
{
|
||||
|
||||
@@ -27,6 +27,11 @@ class InvoiceItem extends Model
|
||||
return $this->belongsTo(Product::class, 'product_id');
|
||||
}
|
||||
|
||||
public function addon()
|
||||
{
|
||||
return $this->belongsTo(Addon::class, 'addon_id');
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
@@ -10,10 +10,12 @@ class RefreshToken extends Model
|
||||
'customer_id',
|
||||
'token',
|
||||
'expires_at',
|
||||
'revoked_at',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'expires_at' => 'datetime',
|
||||
'revoked_at' => 'datetime',
|
||||
];
|
||||
|
||||
public function customer()
|
||||
|
||||
@@ -30,6 +30,7 @@ class ReinstallLog extends Model
|
||||
'started_at' => 'datetime',
|
||||
'completed_at' => 'datetime',
|
||||
'password_supplied_by_customer' => 'boolean',
|
||||
'plain_password' => 'encrypted',
|
||||
];
|
||||
|
||||
public const PRODUCT_TYPE_VPS = 4;
|
||||
|
||||
@@ -20,6 +20,11 @@ class Service extends Model
|
||||
|
||||
protected $table = 'services';
|
||||
|
||||
public const HOSTING_ACCOUNT_RELATIONS = [
|
||||
'hostingAccount.server:id,name,ip_address',
|
||||
'hostingAccount.domain:id,domain_name',
|
||||
];
|
||||
|
||||
protected $fillable = [
|
||||
'uuid',
|
||||
'customer_id',
|
||||
@@ -38,6 +43,8 @@ class Service extends Model
|
||||
'refunded_at',
|
||||
'retry_requested_at',
|
||||
'note',
|
||||
'requirements',
|
||||
'feedback',
|
||||
'registrar_reference',
|
||||
'kyc_url',
|
||||
'rejection_reason',
|
||||
|
||||
+11
-11
@@ -6,7 +6,7 @@ use App\Traits\LogsActivity;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
use App\Traits\HasUuid;
|
||||
|
||||
class Transaction extends Model
|
||||
@@ -61,12 +61,6 @@ class Transaction extends Model
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* `proof_image` stores either a single relative storage path, or a
|
||||
* JSON-encoded array of paths (admin-created service with multiple
|
||||
* proofs). Resolve both shapes into absolute, browsable URLs so the
|
||||
* raw path string never leaks into the frontend as a literal href.
|
||||
*/
|
||||
public function getProofImageUrlsAttribute(): array
|
||||
{
|
||||
if (! $this->proof_image) {
|
||||
@@ -78,9 +72,15 @@ class Transaction extends Model
|
||||
$paths = [$this->proof_image];
|
||||
}
|
||||
|
||||
return array_values(array_map(
|
||||
fn (string $path) => Storage::disk('public')->url($path),
|
||||
array_filter($paths, fn ($path) => is_string($path) && $path !== '')
|
||||
));
|
||||
$paths = array_values(array_filter($paths, fn ($path) => is_string($path) && $path !== ''));
|
||||
|
||||
return array_map(
|
||||
fn (int $index) => URL::temporarySignedRoute(
|
||||
'admin.transactions.proof-image',
|
||||
now()->addDay(),
|
||||
['transaction' => $this->uuid, 'index' => $index],
|
||||
),
|
||||
array_keys($paths),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,6 +43,11 @@ class RouteServiceProvider extends ServiceProvider
|
||||
->namespace($this->namespace)
|
||||
->group(base_path('routes/api.php'));
|
||||
|
||||
Route::prefix('api')
|
||||
->middleware(['api'])
|
||||
->namespace($this->namespace)
|
||||
->group(base_path('routes/admin-media.php'));
|
||||
|
||||
Route::middleware(['api', 'json.response'])
|
||||
->namespace($this->namespace)
|
||||
->group(base_path('routes/client.php'));
|
||||
|
||||
@@ -25,6 +25,7 @@ class ClientAuthService
|
||||
{
|
||||
// Refresh token lifetime in days
|
||||
const REFRESH_TOKEN_TTL_DAYS = 30;
|
||||
const REFRESH_TOKEN_REUSE_GRACE_SECONDS = 30;
|
||||
|
||||
const VERIFY_MAX_ATTEMPTS = 5;
|
||||
|
||||
@@ -280,9 +281,27 @@ class ClientAuthService
|
||||
|
||||
$record = RefreshToken::where('token', $hash)->first();
|
||||
|
||||
if (!$record || $record->isExpired()) {
|
||||
// Xoá token cũ nếu tồn tại nhưng hết hạn
|
||||
$record?->delete();
|
||||
if (!$record) {
|
||||
throw ValidationException::withMessages([
|
||||
'refresh_token' => ['Refresh token không hợp lệ hoặc đã hết hạn.'],
|
||||
]);
|
||||
}
|
||||
|
||||
$isConcurrentRefresh = $record->revoked_at !== null
|
||||
&& $record->revoked_at->gt(now()->subSeconds(self::REFRESH_TOKEN_REUSE_GRACE_SECONDS));
|
||||
|
||||
if ($record->revoked_at !== null && !$isConcurrentRefresh) {
|
||||
// Token đã rotate rồi mà còn bị dùng lại: có thể đã bị đánh cắp,
|
||||
// thu hồi toàn bộ refresh token của khách này để buộc đăng nhập lại.
|
||||
RefreshToken::where('customer_id', $record->customer_id)->delete();
|
||||
|
||||
throw ValidationException::withMessages([
|
||||
'refresh_token' => ['Refresh token đã được sử dụng, mọi phiên đã bị thu hồi.'],
|
||||
]);
|
||||
}
|
||||
|
||||
if ($record->isExpired()) {
|
||||
$record->delete();
|
||||
|
||||
throw ValidationException::withMessages([
|
||||
'refresh_token' => ['Refresh token không hợp lệ hoặc đã hết hạn.'],
|
||||
@@ -298,8 +317,10 @@ class ClientAuthService
|
||||
]);
|
||||
}
|
||||
|
||||
// Rotation: xoá token cũ
|
||||
$record->delete();
|
||||
// Rotation: đánh dấu đã dùng thay vì xoá, để phát hiện reuse nếu bị dùng lại
|
||||
if (!$isConcurrentRefresh) {
|
||||
RefreshToken::whereKey($record->getKey())->whereNull('revoked_at')->update(['revoked_at' => now()]);
|
||||
}
|
||||
|
||||
// Tạo access token mới
|
||||
$newAccessToken = JWTAuth::fromUser($customer);
|
||||
|
||||
@@ -46,8 +46,7 @@ class DomainOrderService
|
||||
|
||||
$domainName = $this->normalizeDomain($data['domain_name']);
|
||||
$years = max(1, (int) ($data['years'] ?? 1));
|
||||
$pricing = $this->findDomainPricing($domainName);
|
||||
$price = (int) $pricing['firstYear'] * $years;
|
||||
$price = DomainPricing::findByDomain($domainName)->orderPrice($years);
|
||||
$months = $years * 12;
|
||||
|
||||
return DB::transaction(function () use ($customer, $product, $domainName, $price, $months, $years) {
|
||||
@@ -363,17 +362,6 @@ class DomainOrderService
|
||||
// Private helpers
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Find pricing for the given domain using longest-match TLD.
|
||||
* TLDs in settings are stored with a leading dot (e.g. ".com.vn").
|
||||
*
|
||||
* @throws \InvalidArgumentException if no matching TLD found
|
||||
*/
|
||||
private function findDomainPricing(string $domain): array
|
||||
{
|
||||
return DomainPricing::findByDomain($domain)->toDomainArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize: lowercase, trim, strip protocol and path.
|
||||
* "HTTPS://My-Site.COM.VN/path" → "my-site.com.vn"
|
||||
|
||||
@@ -17,6 +17,7 @@ use App\Models\Service;
|
||||
use App\Models\VirtualMachines;
|
||||
use App\Repositories\Api\Order\OrderRepository;
|
||||
use App\Repositories\Api\Service\ServiceRepositoryInterface;
|
||||
use App\Support\RenewalPricing;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -204,6 +205,19 @@ class OrderQueryService
|
||||
return ['ok' => false, 'message' => 'Không thể xác định giá gia hạn dịch vụ.', 'code' => 400];
|
||||
}
|
||||
|
||||
$cycleMonths = OrderHelper::cycleToMonths($orderItem->billing_cycle);
|
||||
$validMonths = RenewalPricing::validMonths($orderItem->billing_cycle);
|
||||
|
||||
if (! in_array($months, $validMonths, true)) {
|
||||
return [
|
||||
'ok' => false,
|
||||
'message' => 'Số tháng gia hạn không hợp lệ với chu kỳ của dịch vụ này. Vui lòng chọn: ' . implode(', ', $validMonths) . ' tháng.',
|
||||
'code' => 422,
|
||||
];
|
||||
}
|
||||
|
||||
$cycles = intdiv($months, $cycleMonths);
|
||||
|
||||
// Gia hạn luôn dùng giá sản phẩm hiện tại trong bảng giá, không dùng giá đã
|
||||
// chốt lúc đặt mua ban đầu — giá cũ chỉ để hiển thị trên đơn hàng/hoá đơn gốc.
|
||||
$currentPrice = $this->productRepo->getPricing((int) $service->product_id, $orderItem->billing_cycle);
|
||||
@@ -211,7 +225,9 @@ class OrderQueryService
|
||||
return ['ok' => false, 'message' => 'Sản phẩm hiện không còn bán, không thể gia hạn.', 'code' => 400];
|
||||
}
|
||||
|
||||
$price = (int) $currentPrice * $months;
|
||||
$renewalPrice = (int) $currentPrice * $cycles;
|
||||
$addonTotal = RenewalPricing::addonTotal($service, $cycles);
|
||||
$price = $renewalPrice + $addonTotal;
|
||||
|
||||
if ($service->invoice_id && Invoice::where('id', $service->invoice_id)
|
||||
->where('invoice_type', 2)
|
||||
@@ -238,7 +254,7 @@ class OrderQueryService
|
||||
$periodStart = $service->expires_at && $service->expires_at->isFuture() ? $service->expires_at->copy() : now();
|
||||
$periodEnd = $periodStart->copy()->addMonths($months);
|
||||
|
||||
$invoice = DB::transaction(function () use ($service, $orderItem, $price, $months, $periodStart, $periodEnd) {
|
||||
$invoice = DB::transaction(function () use ($service, $orderItem, $price, $renewalPrice, $cycles, $months, $periodStart, $periodEnd) {
|
||||
$invoice = Invoice::create([
|
||||
'invoice_number' => OrderHelper::generateOrderNumber('INV'),
|
||||
'customer_id' => $service->customer_id,
|
||||
@@ -261,10 +277,14 @@ class OrderQueryService
|
||||
'description' => 'Gia hạn dịch vụ: ' . ($orderItem->product?->name ?? $service->server_name ?? ''),
|
||||
'months' => $months,
|
||||
'quantity' => 1,
|
||||
'unit_price' => $price,
|
||||
'total_price' => $price,
|
||||
'unit_price' => $renewalPrice,
|
||||
'total_price' => $renewalPrice,
|
||||
]);
|
||||
|
||||
foreach (RenewalPricing::addonInvoiceItems($service, $cycles, $months) as $addonItem) {
|
||||
\App\Models\InvoiceItem::create($addonItem + ['invoice_id' => $invoice->id]);
|
||||
}
|
||||
|
||||
$service->update(['invoice_id' => $invoice->id]);
|
||||
|
||||
return $invoice;
|
||||
|
||||
@@ -5,12 +5,13 @@ namespace App\Services\Api\Order;
|
||||
use App\Enums\Order\OrderStatus;
|
||||
use App\Helpers\OrderHelper;
|
||||
use App\Jobs\Mail\Admin\AdminOrderNotificationJob;
|
||||
use App\Models\Addon;
|
||||
use App\Models\Order;
|
||||
use App\Models\Product;
|
||||
use App\Repositories\Api\Invoice\InvoiceRepository;
|
||||
use App\Repositories\Api\Order\OrderRepository;
|
||||
use App\Repositories\Api\Service\ServiceRepository;
|
||||
use App\Services\InvoicePaymentService;
|
||||
use App\Support\AddonQuantityValidator;
|
||||
use Exception;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
@@ -32,31 +33,31 @@ class OrderService
|
||||
* Validate → calculate price → persist Order + OrderItem + Invoice.
|
||||
*
|
||||
* @return array{order: Order, invoice: \App\Models\Invoice}
|
||||
* @throws Exception
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public function create(array $data, $customer): array
|
||||
{
|
||||
if ($this->orderRepo->hasPendingOrder($customer->id)) {
|
||||
throw new Exception('Bạn có đơn hàng chưa thanh toán. Vui lòng thanh toán trước khi tạo đơn mới.');
|
||||
throw new \InvalidArgumentException('Bạn có đơn hàng chưa thanh toán. Vui lòng thanh toán trước khi tạo đơn mới.');
|
||||
}
|
||||
|
||||
$product = $this->productRepo->find($data['product_id']);
|
||||
if (!$product) {
|
||||
throw new Exception('Sản phẩm không tồn tại.');
|
||||
throw new \InvalidArgumentException('Sản phẩm không tồn tại.');
|
||||
}
|
||||
|
||||
$basePrice = $this->productRepo->getPricing($product->id, $data['billing_cycle']);
|
||||
if (is_null($basePrice)) {
|
||||
throw new Exception('Không tìm thấy giá cho chu kỳ thanh toán này.');
|
||||
throw new \InvalidArgumentException('Không tìm thấy giá cho chu kỳ thanh toán này.');
|
||||
}
|
||||
|
||||
// Resolve addons → enriched meta with price & subtotal
|
||||
$addonsMeta = $this->resolveAddons($data['addons'] ?? []);
|
||||
$addonsMeta = $this->resolveAddons($data['addons'] ?? [], $product);
|
||||
$addonsPrice = array_sum(array_column($addonsMeta, 'subtotal'));
|
||||
$total = $basePrice + $addonsPrice;
|
||||
|
||||
if ($customer->total < $total) {
|
||||
throw new Exception(sprintf(
|
||||
throw new \InvalidArgumentException(sprintf(
|
||||
'Số dư không đủ. Hiện có: %s VNĐ, cần: %s VNĐ.',
|
||||
number_format($customer->total),
|
||||
number_format($total)
|
||||
@@ -101,19 +102,19 @@ class OrderService
|
||||
/**
|
||||
* Debit customer balance → mark Order+Invoice paid → provision Service records.
|
||||
*
|
||||
* @throws Exception
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public function pay(Order $order, string $method): Order
|
||||
{
|
||||
if (in_array($order->status, [OrderStatus::ACTIVE->value, OrderStatus::PROCESSING->value], true)) {
|
||||
throw new Exception('Đơn hàng đã được thanh toán hoặc đang xử lý.');
|
||||
throw new \InvalidArgumentException('Đơn hàng đã được thanh toán hoặc đang xử lý.');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($order, $method) {
|
||||
$customer = $order->customer;
|
||||
|
||||
if ($customer->total < $order->total) {
|
||||
throw new Exception(sprintf(
|
||||
throw new \InvalidArgumentException(sprintf(
|
||||
'Số dư không đủ. Hiện có: %s VNĐ, cần: %s VNĐ.',
|
||||
number_format($customer->total),
|
||||
number_format($order->total)
|
||||
@@ -126,7 +127,7 @@ class OrderService
|
||||
}
|
||||
|
||||
if (! $order->invoice) {
|
||||
throw new Exception('Không tìm thấy hóa đơn của đơn hàng.');
|
||||
throw new \InvalidArgumentException('Không tìm thấy hóa đơn của đơn hàng.');
|
||||
}
|
||||
|
||||
$this->invoicePaymentService->payWithBalance($order->invoice, $customer, $method);
|
||||
@@ -175,25 +176,13 @@ class OrderService
|
||||
*
|
||||
* Input: [['addon_id' => 1, 'qty' => 2], ...]
|
||||
* Output: [['addon_id' => 1, 'qty' => 2, 'price' => 50000, 'subtotal' => 100000], ...]
|
||||
*
|
||||
* @throws \Illuminate\Validation\ValidationException
|
||||
*/
|
||||
private function resolveAddons(array $raw): array
|
||||
private function resolveAddons(array $raw, Product $product): array
|
||||
{
|
||||
$resolved = [];
|
||||
foreach ($raw as $entry) {
|
||||
$addon = Addon::find($entry['addon_id'] ?? null);
|
||||
if (!$addon) {
|
||||
continue;
|
||||
}
|
||||
$qty = max(1, (int) ($entry['qty'] ?? 1));
|
||||
$resolved[] = [
|
||||
'addon_id' => $addon->id,
|
||||
'code' => strtolower((string) $addon->code),
|
||||
'name' => $addon->name,
|
||||
'qty' => $qty,
|
||||
'price' => $addon->price,
|
||||
'subtotal' => $addon->price * $qty,
|
||||
];
|
||||
}
|
||||
return $resolved;
|
||||
$activeAddons = $product->addons()->where('status', true)->get()->keyBy('id');
|
||||
|
||||
return AddonQuantityValidator::resolve($raw, $activeAddons);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,7 +76,13 @@ class CustomerServiceProvisioningService
|
||||
{
|
||||
$services = $this->serviceRepository->filter(
|
||||
['customer_uuid' => $uuid],
|
||||
['product', 'orderItem', 'invoice', 'vmware.os.osGroup'],
|
||||
[
|
||||
'product',
|
||||
'orderItem',
|
||||
'invoice',
|
||||
'vmware.os.osGroup',
|
||||
...Service::HOSTING_ACCOUNT_RELATIONS,
|
||||
],
|
||||
);
|
||||
|
||||
ModuleVmware::resolveVirtualMachineIds($services->pluck('vmware'));
|
||||
|
||||
@@ -9,6 +9,8 @@ use App\Helpers\OrderHelper;
|
||||
use App\Jobs\Hosting\ProvisionHostingAccountJob;
|
||||
use App\Jobs\VirtualMachine\Action\VMJobs;
|
||||
use App\Jobs\VirtualMachine\Create\CreateVirtualMachineJob;
|
||||
use App\Jobs\VirtualMachine\Provision\UpdateVmConfigJob;
|
||||
use App\Http\Services\vCenter as ServiceVCenter;
|
||||
use App\Models\Addon;
|
||||
use App\Models\Customer;
|
||||
use App\Models\Invoice;
|
||||
@@ -19,6 +21,7 @@ use App\Models\ServiceAddon;
|
||||
use App\Models\Transaction;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class InvoicePaymentService
|
||||
@@ -125,6 +128,8 @@ class InvoicePaymentService
|
||||
|
||||
if ((int) $invoice->invoice_type === 2) {
|
||||
$this->activateRenewal($invoice);
|
||||
} elseif ((int) $invoice->invoice_type === 3) {
|
||||
$this->activateUpgrade($invoice);
|
||||
} elseif ($invoice->order) {
|
||||
$this->activateOrder($invoice);
|
||||
}
|
||||
@@ -197,6 +202,8 @@ class InvoicePaymentService
|
||||
|
||||
if ((int) $invoice->invoice_type === 2) {
|
||||
$this->activateRenewal($invoice);
|
||||
} elseif ((int) $invoice->invoice_type === 3) {
|
||||
$this->activateUpgrade($invoice);
|
||||
} elseif ($invoice->order) {
|
||||
$this->activateOrder($invoice);
|
||||
}
|
||||
@@ -385,6 +392,107 @@ class InvoicePaymentService
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges the purchased addons into order_items.addons_meta (so RenewalPricing charges
|
||||
* them on the next renewal) and applies the new absolute CPU/RAM/disk totals to the VM.
|
||||
*/
|
||||
private function activateUpgrade(Invoice $invoice): void
|
||||
{
|
||||
$service = Service::query()
|
||||
->with(['orderItem.product', 'vmware'])
|
||||
->find($invoice->service_id);
|
||||
|
||||
$orderItem = $service?->orderItem;
|
||||
if (! $service || ! $orderItem) {
|
||||
return;
|
||||
}
|
||||
|
||||
$upgradeItems = $invoice->invoiceItems()->where('type', 'upgrade')->get();
|
||||
if ($upgradeItems->isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$meta = collect(is_array($orderItem->addons_meta) ? $orderItem->addons_meta : []);
|
||||
$purchasedCodes = [];
|
||||
|
||||
foreach ($upgradeItems as $item) {
|
||||
$addon = Addon::find($item->addon_id);
|
||||
if (! $addon) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$code = strtolower((string) $addon->code);
|
||||
$purchasedCodes[] = $code;
|
||||
|
||||
$qty = (int) $item->quantity;
|
||||
$index = $meta->search(fn ($entry) => (int) ($entry['addon_id'] ?? 0) === $addon->id);
|
||||
$currentQty = $index === false ? 0 : (int) ($meta->get($index)['qty'] ?? 0);
|
||||
$newQty = $currentQty + $qty;
|
||||
|
||||
$entry = [
|
||||
'addon_id' => $addon->id,
|
||||
'code' => $code,
|
||||
'name' => $addon->name,
|
||||
'qty' => $newQty,
|
||||
'price' => (float) $addon->price,
|
||||
'subtotal' => $newQty * (float) $addon->price,
|
||||
];
|
||||
|
||||
if ($index === false) {
|
||||
$meta->push($entry);
|
||||
} else {
|
||||
$meta->put($index, $entry);
|
||||
}
|
||||
}
|
||||
|
||||
$orderItem->update(['addons_meta' => $meta->values()->all()]);
|
||||
|
||||
$moduleVmware = $service->vmware;
|
||||
if (! $moduleVmware) {
|
||||
return;
|
||||
}
|
||||
|
||||
$addonQtyByCode = $meta->keyBy(fn ($entry) => $entry['code'] ?? '');
|
||||
$product = $orderItem->product;
|
||||
|
||||
if (array_intersect(['cpu', 'ram'], $purchasedCodes)) {
|
||||
$totalCpu = (int) ($product?->cpu ?? 0) + (int) ($addonQtyByCode->get('cpu')['qty'] ?? 0);
|
||||
$totalRam = (int) ($product?->ram ?? 0) + (int) ($addonQtyByCode->get('ram')['qty'] ?? 0);
|
||||
|
||||
UpdateVmConfigJob::dispatch(
|
||||
$moduleVmware->id,
|
||||
(string) $moduleVmware->vmware_id,
|
||||
'',
|
||||
$totalCpu,
|
||||
$totalRam,
|
||||
)->afterCommit();
|
||||
}
|
||||
|
||||
if (in_array('disk', $purchasedCodes, true)) {
|
||||
$totalDisk = (int) ($product?->disk ?? 0) + (int) ($addonQtyByCode->get('disk')['qty'] ?? 0);
|
||||
$vcenter = $moduleVmware->vCenter ?? $moduleVmware->ipAddress?->host?->datacenter?->vCenter;
|
||||
|
||||
if ($vcenter) {
|
||||
DB::afterCommit(function () use ($vcenter, $moduleVmware, $totalDisk, $invoice) {
|
||||
try {
|
||||
$serviceVCenter = new ServiceVCenter();
|
||||
if (! $serviceVCenter->loginServer($vcenter)) {
|
||||
throw new \RuntimeException('vCenter login failed');
|
||||
}
|
||||
$serviceVCenter->UpgradeDiskVirtualMachine($moduleVmware, $totalDisk);
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('activateUpgrade: disk upgrade failed', [
|
||||
'invoice_id' => $invoice->id,
|
||||
'module_vmware_id' => $moduleVmware->id,
|
||||
'total_disk' => $totalDisk,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function attachServiceAddons(Service $service, OrderItem $item): void
|
||||
{
|
||||
if ($service->addons()->exists()) {
|
||||
|
||||
@@ -37,7 +37,7 @@ class InvoiceReminderService
|
||||
}
|
||||
|
||||
$now = $now ?? now();
|
||||
$daysFromDue = $invoice->due_date->copy()->startOfDay()->diffInDays($now->copy()->startOfDay(), false);
|
||||
$daysFromDue = (int) $invoice->due_date->copy()->startOfDay()->diffInDays($now->copy()->startOfDay(), false);
|
||||
|
||||
$offsets = (array) config('billing.reminder_offsets', []);
|
||||
if ($offsets === []) {
|
||||
@@ -95,7 +95,7 @@ class InvoiceReminderService
|
||||
{
|
||||
$now = $now ?? now();
|
||||
$dueDate = $invoice->due_date;
|
||||
$daysLate = $dueDate ? $dueDate->copy()->startOfDay()->diffInDays($now->copy()->startOfDay(), false) : 0;
|
||||
$daysLate = $dueDate ? (int) $dueDate->copy()->startOfDay()->diffInDays($now->copy()->startOfDay(), false) : 0;
|
||||
$outstanding = max(0, (int) $invoice->total - (int) ($invoice->amount_paid ?? 0));
|
||||
|
||||
return [
|
||||
|
||||
@@ -6,7 +6,7 @@ use App\Facades\BaseHelperFacade as BaseHelper;
|
||||
use App\Models\DnsServer;
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use App\Support\TlsHttpClientFactory;
|
||||
|
||||
class PleskService
|
||||
{
|
||||
@@ -17,7 +17,7 @@ class PleskService
|
||||
|
||||
public function client(DnsServer $server, int $timeout = 30): PendingRequest
|
||||
{
|
||||
return Http::withoutVerifying()
|
||||
return TlsHttpClientFactory::plesk()
|
||||
->withBasicAuth($server->username, Crypt::decryptString($server->password))
|
||||
->timeout($timeout);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ use App\Facades\BaseHelperFacade as BaseHelper;
|
||||
use App\Models\DnsServer;
|
||||
use App\Repositories\DnsManager\Server\DnsServerRepositoryInterface;
|
||||
use App\Services\Plesk\PleskDomainService;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use App\Support\TlsHttpClientFactory;
|
||||
use Illuminate\Http\Client\RequestException;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
@@ -77,7 +77,7 @@ class ServerService
|
||||
}
|
||||
|
||||
try {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::plesk()
|
||||
->withBasicAuth($this->server->username, Crypt::decryptString($this->server->password))
|
||||
->timeout(10)
|
||||
->post(
|
||||
@@ -103,7 +103,7 @@ class ServerService
|
||||
}
|
||||
|
||||
try {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::plesk()
|
||||
->withBasicAuth($this->server->username, Crypt::decryptString($this->server->password))
|
||||
->timeout(15)
|
||||
->get(
|
||||
@@ -127,7 +127,7 @@ class ServerService
|
||||
}
|
||||
|
||||
try {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::plesk()
|
||||
->withBasicAuth($this->server->username, Crypt::decryptString($this->server->password))
|
||||
->timeout(10)
|
||||
->put(
|
||||
@@ -153,7 +153,7 @@ class ServerService
|
||||
}
|
||||
|
||||
try {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::plesk()
|
||||
->withBasicAuth($this->server->username, Crypt::decryptString($this->server->password))
|
||||
->timeout(30)
|
||||
->delete(
|
||||
@@ -178,7 +178,7 @@ class ServerService
|
||||
}
|
||||
|
||||
try {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::plesk()
|
||||
->withBasicAuth($data['username'], $data['password'])
|
||||
->timeout(10)
|
||||
->get(BaseHelper::url($data['ip_address']) . $this->entry_points['server']);
|
||||
|
||||
@@ -8,7 +8,7 @@ use App\DTOs\VirtualMachine\Rebuild\RebuildContext;
|
||||
use App\Http\Services\vCenter as VCenterService;
|
||||
use App\Models\ModuleDatastore;
|
||||
use App\Models\vCenter as VCenterModel;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use App\Support\TlsHttpClientFactory;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use RuntimeException;
|
||||
|
||||
@@ -74,7 +74,7 @@ final class VmRebuildCloneService
|
||||
'template' => $ctx->template,
|
||||
]);
|
||||
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->timeout(self::CLONE_TIMEOUT)
|
||||
->connectTimeout(30)
|
||||
->withHeaders([
|
||||
@@ -121,7 +121,7 @@ final class VmRebuildCloneService
|
||||
throw new RuntimeException("Rebuild powerOn: cannot login to vCenter #{$ctx->vcenterId}");
|
||||
}
|
||||
|
||||
$powerResp = Http::withoutVerifying()
|
||||
$powerResp = TlsHttpClientFactory::vCenter()
|
||||
->timeout(self::POWER_ON_TIMEOUT)
|
||||
->withHeaders(['vmware-api-session-id' => $this->vCenter->token])
|
||||
->post("https://{$this->vCenter->apiUri}/rest/vcenter/vm/{$ctx->newVmId}/power/start");
|
||||
@@ -138,7 +138,7 @@ final class VmRebuildCloneService
|
||||
]);
|
||||
|
||||
for ($i = 1; $i <= self::TOOLS_MAX_ATTEMPTS; $i++) {
|
||||
$info = Http::withoutVerifying()
|
||||
$info = TlsHttpClientFactory::vCenter()
|
||||
->timeout(10)
|
||||
->withHeaders(['vmware-api-session-id' => $this->vCenter->token])
|
||||
->get("https://{$this->vCenter->apiUri}/rest/vcenter/vm/{$ctx->newVmId}/guest/identity")
|
||||
@@ -185,7 +185,7 @@ final class VmRebuildCloneService
|
||||
}
|
||||
|
||||
try {
|
||||
Http::withoutVerifying()
|
||||
TlsHttpClientFactory::vCenter()
|
||||
->timeout(30)
|
||||
->withHeaders(['vmware-api-session-id' => $this->vCenter->token])
|
||||
->post("https://{$this->vCenter->apiUri}/rest/vcenter/vm/{$ctx->oldVmId}/power/stop");
|
||||
|
||||
@@ -74,6 +74,53 @@ class VmIpReservationService
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reserve a specific, still-free IP within a network (customer-picked change-IP flow).
|
||||
*
|
||||
* @return array{ip_pool_id:int, gateway:string}|null
|
||||
*/
|
||||
public function reserveInNetwork(int $networkId, string $ipAddress, int $serviceId): ?array
|
||||
{
|
||||
return DB::transaction(function () use ($networkId, $ipAddress, $serviceId) {
|
||||
$ipPool = IpPool::where('module_network_id', $networkId)
|
||||
->where('ip_address', $ipAddress)
|
||||
->where('status', 'free')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if (!$ipPool) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$ipPool->update(['status' => 'assigned', 'service_id' => $serviceId]);
|
||||
|
||||
return [
|
||||
'ip_pool_id' => $ipPool->id,
|
||||
'gateway' => (string) ($ipPool->gateway ?? ''),
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
public function freeIpsInNetwork(int $networkId)
|
||||
{
|
||||
return IpPool::where('module_network_id', $networkId)
|
||||
->where('status', 'free')
|
||||
->orderBy('ip_address')
|
||||
->get(['id', 'ip_address', 'gateway']);
|
||||
}
|
||||
|
||||
public function releaseByPoolId(int $ipPoolId): void
|
||||
{
|
||||
try {
|
||||
IpPool::where('id', $ipPoolId)->update(['status' => 'free', 'service_id' => null]);
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('VmIpReservationService: releaseByPoolId failed', [
|
||||
'ip_pool_id' => $ipPoolId,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function release(ModuleIpAddress $reservation, ?int $ipPoolId): void
|
||||
{
|
||||
try {
|
||||
|
||||
@@ -5,7 +5,7 @@ declare(strict_types=1);
|
||||
namespace App\Services\VirtualMachine;
|
||||
|
||||
use App\Http\Services\vCenter;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use App\Support\TlsHttpClientFactory;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Throwable;
|
||||
|
||||
@@ -18,7 +18,7 @@ class VmPowerService
|
||||
return 'Login_Again';
|
||||
}
|
||||
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders(['vmware-api-session-id' => $vCenter->token])
|
||||
->post("https://{$vCenter->apiUri}/rest/vcenter/vm/{$vmId}/power/start");
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ namespace App\Services;
|
||||
use App\Http\Facade\SignRSA;
|
||||
use App\Http\Services\vCenter as VCenterService;
|
||||
use App\Models\ModuleVmware;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use App\Support\TlsHttpClientFactory;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
final class VmProvisionService
|
||||
@@ -38,7 +38,7 @@ final class VmProvisionService
|
||||
public function getVmGuestInfo(VCenterService $service, string $vmId): array
|
||||
{
|
||||
try {
|
||||
$response = Http::withoutVerifying()
|
||||
$response = TlsHttpClientFactory::vCenter()
|
||||
->withHeaders(['vmware-api-session-id' => $service->token])
|
||||
->timeout(10)
|
||||
->get("https://{$service->apiUri}/rest/vcenter/vm/{$vmId}/guest/identity");
|
||||
|
||||
@@ -6,6 +6,8 @@ namespace App\Services;
|
||||
|
||||
use App\Http\Facade\SignRSA;
|
||||
use App\Models\InfraManagement;
|
||||
use App\Support\PowerShellEscaper;
|
||||
use App\Support\SshHostKeyVerifier;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use phpseclib3\Net\SSH2;
|
||||
|
||||
@@ -207,6 +209,8 @@ final class VsphereHostSshService
|
||||
|
||||
$client = new SSH2($config['host'], $config['port'], self::CONNECT_TIMEOUT);
|
||||
|
||||
SshHostKeyVerifier::verify($client, $config['host']);
|
||||
|
||||
if (!$client->login($config['username'], $config['password'])) {
|
||||
throw new \RuntimeException(
|
||||
"SSH login failed: {$config['host']}:{$config['port']}"
|
||||
@@ -364,23 +368,14 @@ final class VsphereHostSshService
|
||||
*/
|
||||
private function windowsPowerShellCommand(string $workingDirectory, string $script, array $arguments): string
|
||||
{
|
||||
return sprintf(
|
||||
'powershell -ExecutionPolicy Bypass -NonInteractive -File "%s\\%s" %s',
|
||||
$workingDirectory,
|
||||
$script,
|
||||
implode(' ', array_map(
|
||||
fn (string $argument): string => $this->warg($argument),
|
||||
$arguments,
|
||||
)),
|
||||
);
|
||||
}
|
||||
$scriptPath = $workingDirectory . '\\' . $script;
|
||||
$psScript = '& ' . PowerShellEscaper::singleQuote($scriptPath) . ' ' . implode(' ', array_map(
|
||||
fn (string $argument): string => PowerShellEscaper::singleQuote($argument),
|
||||
$arguments,
|
||||
));
|
||||
|
||||
/**
|
||||
* Windows cmd.exe safe argument: wrap in double quotes, escape inner double quotes.
|
||||
*/
|
||||
private function warg(string $value): string
|
||||
{
|
||||
return '"' . str_replace('"', '\\"', $value) . '"';
|
||||
return 'powershell -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand '
|
||||
. PowerShellEscaper::encodedCommand($psScript);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
use App\Models\Addon;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class AddonQuantityValidator
|
||||
{
|
||||
/**
|
||||
* @param array<int, array{addon_id?: int, qty?: int}> $raw
|
||||
* @param Collection<int, Addon> $activeAddons Keyed by addon id.
|
||||
* @param array<int, int> $existingQtyByAddonId Already-owned qty per addon id, for capping total against max.
|
||||
* @return list<array{addon_id: int, code: string, name: string, qty: int, price: float, subtotal: float}>
|
||||
*
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public static function resolve(array $raw, Collection $activeAddons, array $existingQtyByAddonId = []): array
|
||||
{
|
||||
$resolved = [];
|
||||
|
||||
foreach ($raw as $entry) {
|
||||
$addonId = $entry['addon_id'] ?? null;
|
||||
if (!$addonId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$addon = $activeAddons->get($addonId);
|
||||
if (!$addon) {
|
||||
throw ValidationException::withMessages([
|
||||
'addons' => ['Addon không tồn tại hoặc không áp dụng cho sản phẩm này.'],
|
||||
]);
|
||||
}
|
||||
|
||||
$qty = (int) ($entry['qty'] ?? 1);
|
||||
|
||||
if ($qty < $addon->min) {
|
||||
throw ValidationException::withMessages([
|
||||
'addons' => ["Số lượng addon {$addon->name} phải lớn hơn hoặc bằng {$addon->min}."],
|
||||
]);
|
||||
}
|
||||
|
||||
$totalQty = ($existingQtyByAddonId[$addonId] ?? 0) + $qty;
|
||||
|
||||
if ($addon->max > 0 && $totalQty > $addon->max) {
|
||||
throw ValidationException::withMessages([
|
||||
'addons' => ["Số lượng addon {$addon->name} không được vượt quá {$addon->max}."],
|
||||
]);
|
||||
}
|
||||
|
||||
if ($addon->step > 0 && $qty % $addon->step !== 0) {
|
||||
throw ValidationException::withMessages([
|
||||
'addons' => ["Số lượng addon {$addon->name} phải là bội số của {$addon->step}."],
|
||||
]);
|
||||
}
|
||||
|
||||
$resolved[] = [
|
||||
'addon_id' => $addon->id,
|
||||
'code' => strtolower((string) $addon->code),
|
||||
'name' => $addon->name,
|
||||
'qty' => $qty,
|
||||
'price' => $addon->price,
|
||||
'subtotal' => $addon->price * $qty,
|
||||
];
|
||||
}
|
||||
|
||||
return $resolved;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
final class PowerCliCertificatePolicy
|
||||
{
|
||||
public static function configurationLine(): string
|
||||
{
|
||||
$action = config('vmware.tls_verify', true) ? 'Fail' : 'Ignore';
|
||||
|
||||
return "Set-PowerCLIConfiguration -InvalidCertificateAction {$action} -Scope Session -Confirm:\$false | Out-Null";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
final class PowerShellEscaper
|
||||
{
|
||||
public static function singleQuote(string $value): string
|
||||
{
|
||||
return "'" . str_replace("'", "''", $value) . "'";
|
||||
}
|
||||
|
||||
public static function encodedCommand(string $script): string
|
||||
{
|
||||
return base64_encode(mb_convert_encoding($script, 'UTF-16LE', 'UTF-8'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
use App\Helpers\OrderHelper;
|
||||
use App\Models\Addon;
|
||||
use App\Models\Service;
|
||||
|
||||
class RenewalPricing
|
||||
{
|
||||
/** @return list<int> */
|
||||
public static function validMonths(string $billingCycle): array
|
||||
{
|
||||
$cycleMonths = OrderHelper::cycleToMonths($billingCycle);
|
||||
|
||||
if ($cycleMonths > 24) {
|
||||
return [$cycleMonths];
|
||||
}
|
||||
|
||||
$maxMultiple = intdiv(24, $cycleMonths);
|
||||
|
||||
return array_map(static fn (int $n): int => $n * $cycleMonths, range(1, $maxMultiple));
|
||||
}
|
||||
|
||||
public static function addonTotal(Service $service, int $cycles): int
|
||||
{
|
||||
return (int) array_sum(array_column(self::addonInvoiceItems($service, $cycles, 0), 'total_price'));
|
||||
}
|
||||
|
||||
/** @return list<array<string, mixed>> */
|
||||
public static function addonInvoiceItems(Service $service, int $cycles, int $months): array
|
||||
{
|
||||
$meta = array_filter(
|
||||
(array) ($service->orderItem?->addons_meta ?? []),
|
||||
static fn ($entry): bool => is_array($entry) && (int) ($entry['qty'] ?? 0) > 0,
|
||||
);
|
||||
|
||||
if ($meta === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$currentPrices = Addon::whereIn('id', array_column($meta, 'addon_id'))->pluck('price', 'id');
|
||||
|
||||
$items = [];
|
||||
foreach ($meta as $entry) {
|
||||
$qty = (int) $entry['qty'];
|
||||
$unitPrice = (int) ($currentPrices[$entry['addon_id'] ?? null] ?? $entry['price'] ?? 0);
|
||||
$totalPrice = $unitPrice * $qty * $cycles;
|
||||
|
||||
if ($totalPrice <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$items[] = [
|
||||
'product_id' => $service->product_id,
|
||||
'type' => 'addon',
|
||||
'description' => 'Addon: ' . ($entry['name'] ?? strtoupper((string) ($entry['code'] ?? ''))) . ' x' . $qty,
|
||||
'months' => $months,
|
||||
'quantity' => $qty,
|
||||
'unit_price' => $unitPrice * $cycles,
|
||||
'total_price' => $totalPrice,
|
||||
];
|
||||
}
|
||||
|
||||
return $items;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
use phpseclib3\Net\SSH2;
|
||||
use RuntimeException;
|
||||
|
||||
final class SshHostKeyVerifier
|
||||
{
|
||||
/** @throws RuntimeException */
|
||||
public static function verify(SSH2 $client, string $host): void
|
||||
{
|
||||
$knownHostsPath = config('vmware.ssh_known_hosts');
|
||||
if (!$knownHostsPath) {
|
||||
if (config('vmware.tls_verify', true)) {
|
||||
throw new RuntimeException("SSH host key verification required for {$host}: set VCENTER_SSH_KNOWN_HOSTS or VCENTER_TLS_VERIFY=false");
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!is_readable($knownHostsPath)) {
|
||||
throw new RuntimeException("SSH known_hosts file not readable: {$knownHostsPath}");
|
||||
}
|
||||
|
||||
$serverKey = (string) $client->getServerPublicHostKey();
|
||||
$serverKeyParts = preg_split('/\s+/', trim($serverKey));
|
||||
$serverKeyValue = $serverKeyParts[1] ?? $serverKey;
|
||||
|
||||
$lines = file($knownHostsPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
|
||||
foreach ($lines as $line) {
|
||||
$parts = preg_split('/\s+/', trim($line));
|
||||
if (count($parts) < 3 || $parts[0] !== $host) {
|
||||
continue;
|
||||
}
|
||||
if (hash_equals($parts[2], $serverKeyValue)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
throw new RuntimeException("SSH host key verification failed for {$host}: no matching known_hosts entry");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
|
||||
final class TlsHttpClientFactory
|
||||
{
|
||||
public static function vCenter(): PendingRequest
|
||||
{
|
||||
return Http::withOptions(['verify' => self::verifyOption('vmware')]);
|
||||
}
|
||||
|
||||
public static function plesk(): PendingRequest
|
||||
{
|
||||
return Http::withOptions(['verify' => self::verifyOption('services.plesk')]);
|
||||
}
|
||||
|
||||
/** @return array<int, mixed> */
|
||||
public static function vCenterCurlOptions(): array
|
||||
{
|
||||
$verify = self::verifyOption('vmware');
|
||||
|
||||
return array_filter([
|
||||
CURLOPT_SSL_VERIFYPEER => $verify !== false,
|
||||
CURLOPT_SSL_VERIFYHOST => $verify === false ? 0 : 2,
|
||||
CURLOPT_CAINFO => is_string($verify) ? $verify : null,
|
||||
], fn ($value) => $value !== null);
|
||||
}
|
||||
|
||||
private static function verifyOption(string $configKey): bool|string
|
||||
{
|
||||
if (!config("{$configKey}.tls_verify", true)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return config("{$configKey}.ca_bundle") ?: true;
|
||||
}
|
||||
}
|
||||
+20
-17
@@ -8,32 +8,32 @@
|
||||
],
|
||||
"license": "MIT",
|
||||
"require": {
|
||||
"php": "^8.1",
|
||||
"php": "^8.2",
|
||||
"ext-openssl": "*",
|
||||
"barryvdh/laravel-dompdf": "^3.1",
|
||||
"darkaonline/l5-swagger": "^8.6",
|
||||
"darkaonline/l5-swagger": "^9.0",
|
||||
"guzzlehttp/guzzle": "^7.2",
|
||||
"kalnoy/nestedset": "^6.0",
|
||||
"laravel/framework": "^10.0",
|
||||
"laravel/horizon": "^5.4.0",
|
||||
"laravel/tinker": "^2.7",
|
||||
"kalnoy/nestedset": "^6.0.5",
|
||||
"laravel/framework": "^12.61.1",
|
||||
"laravel/horizon": "^5.30",
|
||||
"laravel/tinker": "^2.10",
|
||||
"maatwebsite/excel": "^3.1",
|
||||
"nwidart/laravel-modules": "^10.0",
|
||||
"opcodesio/log-viewer": "^3.18",
|
||||
"nwidart/laravel-modules": "^12.0",
|
||||
"opcodesio/log-viewer": "^3.15",
|
||||
"phpoffice/phpword": "^1.4",
|
||||
"phpseclib/phpseclib": "*",
|
||||
"phpseclib/phpseclib": "^3.0",
|
||||
"plesk/ext-laravel-integration": "^7.0",
|
||||
"predis/predis": "^2.2",
|
||||
"pusher/pusher-php-server": "^7.2",
|
||||
"spatie/laravel-permission": "^6.3",
|
||||
"tymon/jwt-auth": "^2.0"
|
||||
"spatie/laravel-permission": "^6.16",
|
||||
"tymon/jwt-auth": "^2.2"
|
||||
},
|
||||
"require-dev": {
|
||||
"fakerphp/faker": "^1.9.1",
|
||||
"laravel/sail": "^1.0.1",
|
||||
"mockery/mockery": "^1.4.4",
|
||||
"nunomaduro/collision": "^7.12",
|
||||
"phpunit/phpunit": "^9.5.10",
|
||||
"fakerphp/faker": "^1.23",
|
||||
"laravel/sail": "^1.41",
|
||||
"mockery/mockery": "^1.6",
|
||||
"nunomaduro/collision": "^8.6",
|
||||
"phpunit/phpunit": "^11.5",
|
||||
"spatie/laravel-ignition": "^2.9"
|
||||
},
|
||||
"autoload": {
|
||||
@@ -77,7 +77,10 @@
|
||||
"preferred-install": "dist",
|
||||
"sort-packages": true,
|
||||
"platform": {
|
||||
"php": "8.1.0"
|
||||
"php": "8.2.0"
|
||||
},
|
||||
"allow-plugins": {
|
||||
"wikimedia/composer-merge-plugin": true
|
||||
}
|
||||
},
|
||||
"minimum-stability": "dev",
|
||||
|
||||
Generated
+1736
-1336
File diff suppressed because it is too large
Load Diff
@@ -128,6 +128,8 @@ return [
|
||||
|
||||
'key' => env('APP_KEY'),
|
||||
|
||||
'previous_keys' => array_filter(explode(',', (string) env('APP_PREVIOUS_KEYS', ''))),
|
||||
|
||||
'cipher' => 'AES-256-CBC',
|
||||
|
||||
/*
|
||||
|
||||
@@ -67,9 +67,9 @@ return [
|
||||
* Middleware allows to prevent unexpected access to API documentation
|
||||
*/
|
||||
'middleware' => [
|
||||
'api' => [],
|
||||
'asset' => [],
|
||||
'docs' => [],
|
||||
'api' => ['restrict.local'],
|
||||
'asset' => ['restrict.local'],
|
||||
'docs' => ['restrict.local'],
|
||||
'oauth2_callback' => [],
|
||||
],
|
||||
|
||||
|
||||
@@ -4,4 +4,6 @@ return [
|
||||
'key' => env('RSA_KEY'),
|
||||
'public' => env('RSA_PUBLIC'),
|
||||
'private' => env('RSA_PRIVATE'),
|
||||
'previous_key' => env('RSA_PREVIOUS_KEY'),
|
||||
'previous_public' => env('RSA_PREVIOUS_PUBLIC'),
|
||||
];
|
||||
|
||||
@@ -30,6 +30,11 @@ return [
|
||||
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
|
||||
],
|
||||
|
||||
'plesk' => [
|
||||
'tls_verify' => env('PLESK_TLS_VERIFY', true),
|
||||
'ca_bundle' => env('PLESK_CA_BUNDLE'),
|
||||
],
|
||||
|
||||
'nextjs' => [
|
||||
'url' => env('NEXTJS_URL', 'http://localhost:3000'),
|
||||
'revalidate_secret' => env('NEXTJS_REVALIDATE_SECRET'),
|
||||
|
||||
@@ -4,6 +4,16 @@ return [
|
||||
// Default password baked into every VM template at clone time.
|
||||
'template_password' => env('VMWARE_TEMPLATE_PASSWORD', 'TGS@123'),
|
||||
|
||||
// TLS verification for vCenter/ESXi REST calls and PowerCLI sessions.
|
||||
// Default true (secure). Set VCENTER_TLS_VERIFY=false only where the
|
||||
// jump host truly cannot validate the vCenter cert yet.
|
||||
'tls_verify' => env('VCENTER_TLS_VERIFY', true),
|
||||
'ca_bundle' => env('VCENTER_CA_BUNDLE'),
|
||||
|
||||
// known_hosts file for SSH to the jump host and vSphere hosts. Required
|
||||
// while tls_verify is true; skipped only when tls_verify is false.
|
||||
'ssh_known_hosts' => env('VCENTER_SSH_KNOWN_HOSTS'),
|
||||
|
||||
// HAProxy (console.tgs.com.vn) routes WMKS console websockets to the
|
||||
// ESXi host that owns the ticket via the `?host=` query param — see
|
||||
// ha-proxy.md. This maps each ESXi IP to the domain HAProxy matches on.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user