update auth

This commit is contained in:
pbao9
2025-08-05 08:58:40 +07:00
parent fc277e5ef6
commit 1a9ade38e8
6 changed files with 81 additions and 54 deletions
+7
View File
@@ -65,6 +65,13 @@ if (!function_exists('customer')) {
} }
} }
if (!function_exists('user')) {
function user()
{
return Auth::guard('users')->user();
}
}
if (!function_exists('generate_order_number')) { if (!function_exists('generate_order_number')) {
/** /**
* Generate a unique order number with given prefix * Generate a unique order number with given prefix
+1 -1
View File
@@ -33,7 +33,7 @@ return [
| |
*/ */
'guard' => ['admins'], 'guard' => ['admins', 'users'],
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
@@ -2,7 +2,7 @@
<!-- Avatar --> <!-- Avatar -->
<button @click="open = !open" @click.away="open = false" <button @click="open = !open" @click.away="open = false"
class="w-8 h-8 rounded-full overflow-hidden shadow-lg image-fit zoom-in focus:outline-none"> class="w-8 h-8 rounded-full overflow-hidden shadow-lg image-fit zoom-in focus:outline-none">
<img src="{{ asset('template/' . customer()?->avatar) ?? asset('images/avatar.png') }}" alt="Avatar"> <img src="{{ asset('images/avatar.png') }}" alt="Avatar">
</button> </button>
<!-- Dropdown --> <!-- Dropdown -->
-1
View File
@@ -79,7 +79,6 @@
@include("frontend.sidebar") @include("frontend.sidebar")
<div class="main content-wrapper d-flex flex-column align-items-stretch flex-shrink-0 bg-white p-3 px-lg-5"> <div class="main content-wrapper d-flex flex-column align-items-stretch flex-shrink-0 bg-white p-3 px-lg-5">
<h1>{{ $title }}</h1> <h1>{{ $title }}</h1>
@include("alerts")
@yield("content") @yield("content")
</div> </div>
@include("frontend.footer") @include("frontend.footer")
@@ -112,10 +112,9 @@
const getTicket = new Promise((resolve, reject) => { const getTicket = new Promise((resolve, reject) => {
$.ajax({ $.ajax({
url: '{{ route('api.GetConsoleTicket') }}', url: '{{ route('api.user.GetConsoleTicket') }}',
type: 'get', type: 'get',
headers: { headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}',
'Accept': 'application/json', 'Accept': 'application/json',
'Authorization': 'Bearer {{ request()->cookie('aut_accessToken') }}' 'Authorization': 'Bearer {{ request()->cookie('aut_accessToken') }}'
}, },
@@ -128,6 +127,10 @@
} else { } else {
reject(response.message) reject(response.message)
} }
},
error: function(xhr, status, error) {
console.error('API Error:', xhr.responseText);
reject('API request failed: ' + error);
} }
}) })
}); });
+67 -49
View File
@@ -458,7 +458,7 @@ Route::prefix('v1')
}) })
/* Api for customer */ /* Api for customer */
->group(function () { ->group(function () {
Route::middleware('auth:sanctum') Route::middleware(['auth:sanctum'])
->group(function () { ->group(function () {
Route::post('get-status-virtual-machine', function (Request $request, ServiceVCenter $serviceVCenter) { Route::post('get-status-virtual-machine', function (Request $request, ServiceVCenter $serviceVCenter) {
$vmware_id = $request->vmware_id; $vmware_id = $request->vmware_id;
@@ -899,6 +899,24 @@ Route::prefix('v1')
return response()->json(['error' => true, 'message' => "Can't find product"]); return response()->json(['error' => true, 'message' => "Can't find product"]);
} }
// Validate that the product belongs to the authenticated user
if ($product->customer_id != user()->id) {
return response()->json([
'error' => true,
'message' => 'Không có quyền truy cập máy ảo này'
]);
}
// Check if service is expired
if ($product->status == 4) {
return response()->json(['error' => true, 'message' => 'Dịch vụ đã hết hạn']);
}
// Check if VM is still initializing
if ($product->status == 3) {
return response()->json(['error' => true, 'message' => 'Máy ảo đang khởi tạo']);
}
$vcenter = null; $vcenter = null;
if ($product->ipAddress && $product->ipAddress->host && $product->ipAddress->host->datacenter && $product->ipAddress->host->datacenter->vCenter) { if ($product->ipAddress && $product->ipAddress->host && $product->ipAddress->host->datacenter && $product->ipAddress->host->datacenter->vCenter) {
$vcenter = $product->ipAddress->host->datacenter->vCenter; $vcenter = $product->ipAddress->host->datacenter->vCenter;
@@ -1149,7 +1167,7 @@ Route::prefix('v1')
$validator = Validator::make($request->all(), [ $validator = Validator::make($request->all(), [
'vm_id' => 'required|string|max:255', 'vm_id' => 'required|string|max:255',
]); ]);
if ($validator->fails()) { if ($validator->fails()) {
return response()->json([ return response()->json([
'error' => true, 'error' => true,
@@ -1157,63 +1175,63 @@ Route::prefix('v1')
'errors' => $validator->errors() 'errors' => $validator->errors()
], 422); ], 422);
} }
$vmId = $request->input('vm_id'); $vmId = $request->input('vm_id');
$vm = ModuleVmware::where('vmware_id', $vmId) $vm = ModuleVmware::where('vmware_id', $vmId)
->orWhere('id', $vmId) ->orWhere('id', $vmId)
->first(); ->first();
if (!$vm) { if (!$vm) {
return response()->json([ return response()->json([
'error' => true, 'error' => true,
'message' => 'Không tìm thấy thông tin máy ảo' 'message' => 'Không tìm thấy thông tin máy ảo'
], 404); ], 404);
} }
if ($vm->status == 4) { if ($vm->status == 4) {
return response()->json([ return response()->json([
'error' => true, 'error' => true,
'message' => 'Dịch vụ đã hết hạn' 'message' => 'Dịch vụ đã hết hạn'
], 400); ], 400);
} }
if ($vm->status == 3) { if ($vm->status == 3) {
return response()->json([ return response()->json([
'error' => true, 'error' => true,
'message' => 'Máy ảo đang khởi tạo' 'message' => 'Máy ảo đang khởi tạo'
], 400); ], 400);
} }
$vcenter = $vm->ipAddress->host->datacenter->vCenter ?? null; $vcenter = $vm->ipAddress->host->datacenter->vCenter ?? null;
if (!$vcenter) { if (!$vcenter) {
return response()->json([ return response()->json([
'error' => true, 'error' => true,
'message' => 'Không tìm thấy thông tin vCenter' 'message' => 'Không tìm thấy thông tin vCenter'
], 500); ], 500);
} }
if (!$serviceVCenter->loginServer($vcenter)) { if (!$serviceVCenter->loginServer($vcenter)) {
return response()->json([ return response()->json([
'error' => true, 'error' => true,
'message' => 'Không thể đăng nhập vào vCenter' 'message' => 'Không thể đăng nhập vào vCenter'
], 500); ], 500);
} }
// Gọi 2 endpoint // Gọi 2 endpoint
$identity = Http::withoutVerifying() $identity = Http::withoutVerifying()
->withHeaders(['vmware-api-session-id' => $serviceVCenter->token]) ->withHeaders(['vmware-api-session-id' => $serviceVCenter->token])
->get("https://{$serviceVCenter->apiUri}/rest/vcenter/vm/{$vm->vmware_id}/guest/identity") ->get("https://{$serviceVCenter->apiUri}/rest/vcenter/vm/{$vm->vmware_id}/guest/identity")
->json(); ->json();
$networking = Http::withoutVerifying() $networking = Http::withoutVerifying()
->withHeaders(['vmware-api-session-id' => $serviceVCenter->token]) ->withHeaders(['vmware-api-session-id' => $serviceVCenter->token])
->get("https://{$serviceVCenter->apiUri}/rest/vcenter/vm/{$vm->vmware_id}/guest/networking") ->get("https://{$serviceVCenter->apiUri}/rest/vcenter/vm/{$vm->vmware_id}/guest/networking")
->json(); ->json();
// Parse IP // Parse IP
$ipAddresses = []; $ipAddresses = [];
// (1) Từ networking // (1) Từ networking
if (isset($networking['value']['interfaces'])) { if (isset($networking['value']['interfaces'])) {
foreach ($networking['value']['interfaces'] as $interface) { foreach ($networking['value']['interfaces'] as $interface) {
@@ -1228,7 +1246,7 @@ Route::prefix('v1')
} }
} }
} }
// (2) Nếu networking rỗng, fallback từ identity // (2) Nếu networking rỗng, fallback từ identity
if (empty($ipAddresses) && isset($identity['value']['ip_address'])) { if (empty($ipAddresses) && isset($identity['value']['ip_address'])) {
$ip = $identity['value']['ip_address']; $ip = $identity['value']['ip_address'];
@@ -1240,12 +1258,12 @@ Route::prefix('v1')
]; ];
} }
} }
// Update trạng thái // Update trạng thái
if (!empty($ipAddresses)) { if (!empty($ipAddresses)) {
$vm->update(['status' => 1]); $vm->update(['status' => 1]);
} }
return response()->json([ return response()->json([
'error' => false, 'error' => false,
'message' => 'Lấy IP address thành công', 'message' => 'Lấy IP address thành công',
@@ -1261,27 +1279,27 @@ Route::prefix('v1')
] ]
] ]
]); ]);
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('❌ Lỗi khi lấy IP address của VM', [ Log::error('❌ Lỗi khi lấy IP address của VM', [
'vm_id' => $request->input('vm_id'), 'vm_id' => $request->input('vm_id'),
'error' => $e->getMessage(), 'error' => $e->getMessage(),
'trace' => $e->getTraceAsString() 'trace' => $e->getTraceAsString()
]); ]);
return response()->json([ return response()->json([
'error' => true, 'error' => true,
'message' => 'Lỗi hệ thống: ' . $e->getMessage() 'message' => 'Lỗi hệ thống: ' . $e->getMessage()
], 500); ], 500);
} }
})->name('api.user.GetIPAddress'); })->name('api.user.GetIPAddress');
Route::get('get-vm-info', function (Request $request, ServiceVCenter $serviceVCenter) { Route::get('get-vm-info', function (Request $request, ServiceVCenter $serviceVCenter) {
try { try {
$validator = Validator::make($request->all(), [ $validator = Validator::make($request->all(), [
'vm_id' => 'required|string|max:255', 'vm_id' => 'required|string|max:255',
]); ]);
if ($validator->fails()) { if ($validator->fails()) {
return response()->json([ return response()->json([
'error' => true, 'error' => true,
@@ -1289,29 +1307,29 @@ Route::prefix('v1')
'errors' => $validator->errors() 'errors' => $validator->errors()
], 422); ], 422);
} }
$vmId = $request->input('vm_id'); $vmId = $request->input('vm_id');
$vcenter = vCenter::first(); $vcenter = vCenter::first();
if (!$vcenter) { if (!$vcenter) {
return response()->json([ return response()->json([
'error' => true, 'error' => true,
'message' => 'Không tìm thấy thông tin vCenter' 'message' => 'Không tìm thấy thông tin vCenter'
], 500); ], 500);
} }
// Sử dụng token có sẵn nếu có // Sử dụng token có sẵn nếu có
$serviceVCenter->apiUri = $vcenter->host; $serviceVCenter->apiUri = $vcenter->host;
$serviceVCenter->token = $vcenter->token; $serviceVCenter->token = $vcenter->token;
// Gọi API với timeout 5s // Gọi API với timeout 5s
$vmInfo = Http::withoutVerifying() $vmInfo = Http::withoutVerifying()
->timeout(5) ->timeout(5)
->withHeaders(['vmware-api-session-id' => $serviceVCenter->token]) ->withHeaders(['vmware-api-session-id' => $serviceVCenter->token])
->get("https://{$serviceVCenter->apiUri}/rest/vcenter/vm/{$vmId}") ->get("https://{$serviceVCenter->apiUri}/rest/vcenter/vm/{$vmId}")
->json(); ->json();
// Nếu token hết hạn, login lại 1 lần duy nhất // Nếu token hết hạn, login lại 1 lần duy nhất
if (isset($vmInfo['type']) && str_contains($vmInfo['value']['messages'][0]['default_message'] ?? '', 'session')) { if (isset($vmInfo['type']) && str_contains($vmInfo['value']['messages'][0]['default_message'] ?? '', 'session')) {
if (!$serviceVCenter->loginServer($vcenter)) { if (!$serviceVCenter->loginServer($vcenter)) {
@@ -1320,7 +1338,7 @@ Route::prefix('v1')
'message' => 'Không thể đăng nhập vào vCenter' 'message' => 'Không thể đăng nhập vào vCenter'
], 500); ], 500);
} }
// Thử lại với token mới // Thử lại với token mới
$vmInfo = Http::withoutVerifying() $vmInfo = Http::withoutVerifying()
->timeout(5) ->timeout(5)
@@ -1328,14 +1346,14 @@ Route::prefix('v1')
->get("https://{$serviceVCenter->apiUri}/rest/vcenter/vm/{$vmId}") ->get("https://{$serviceVCenter->apiUri}/rest/vcenter/vm/{$vmId}")
->json(); ->json();
} }
if (isset($vmInfo['type'])) { if (isset($vmInfo['type'])) {
return response()->json([ return response()->json([
'error' => true, 'error' => true,
'message' => 'Không thể lấy thông tin VM từ vCenter' 'message' => 'Không thể lấy thông tin VM từ vCenter'
], 500); ], 500);
} }
return response()->json([ return response()->json([
'error' => false, 'error' => false,
'message' => 'Lấy thông tin VM thành công', 'message' => 'Lấy thông tin VM thành công',
@@ -1353,7 +1371,7 @@ Route::prefix('v1')
'size_MiB' => $vmInfo['value']['memory']['size_MiB'] ?? 0, 'size_MiB' => $vmInfo['value']['memory']['size_MiB'] ?? 0,
'hot_add_enabled' => $vmInfo['value']['memory']['hot_add_enabled'] ?? false, 'hot_add_enabled' => $vmInfo['value']['memory']['hot_add_enabled'] ?? false,
], ],
'disks' => array_map(function($disk) { 'disks' => array_map(function ($disk) {
return [ return [
'key' => $disk['key'] ?? '', 'key' => $disk['key'] ?? '',
'label' => $disk['value']['label'] ?? '', 'label' => $disk['value']['label'] ?? '',
@@ -1361,7 +1379,7 @@ Route::prefix('v1')
'type' => $disk['value']['type'] ?? '', 'type' => $disk['value']['type'] ?? '',
]; ];
}, $vmInfo['value']['disks'] ?? []), }, $vmInfo['value']['disks'] ?? []),
'nics' => array_map(function($nic) { 'nics' => array_map(function ($nic) {
return [ return [
'key' => $nic['key'] ?? '', 'key' => $nic['key'] ?? '',
'label' => $nic['value']['label'] ?? '', 'label' => $nic['value']['label'] ?? '',
@@ -1385,32 +1403,32 @@ Route::prefix('v1')
], ],
'raw_data' => $vmInfo['value'] ?? null 'raw_data' => $vmInfo['value'] ?? null
]); ]);
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('❌ Lỗi khi lấy thông tin VM', [ Log::error('❌ Lỗi khi lấy thông tin VM', [
'vm_id' => $request->input('vm_id'), 'vm_id' => $request->input('vm_id'),
'error' => $e->getMessage(), 'error' => $e->getMessage(),
'trace' => $e->getTraceAsString() 'trace' => $e->getTraceAsString()
]); ]);
return response()->json([ return response()->json([
'error' => true, 'error' => true,
'message' => 'Lỗi hệ thống: ' . $e->getMessage() 'message' => 'Lỗi hệ thống: ' . $e->getMessage()
], 500); ], 500);
} }
})->name('api.user.GetVMInfo'); })->name('api.user.GetVMInfo');
Route::get('get-vm-info/{vm_id}/{params?}', function (Request $request, ServiceVCenter $serviceVCenter, $vm_id, $params = null) { Route::get('get-vm-info/{vm_id}/{params?}', function (Request $request, ServiceVCenter $serviceVCenter, $vm_id, $params = null) {
try { try {
$vcenter = vCenter::first(); $vcenter = vCenter::first();
if (!$vcenter) { if (!$vcenter) {
return response()->json([ return response()->json([
'error' => true, 'error' => true,
'message' => __('vCenter configuration not found') 'message' => __('vCenter configuration not found')
], 500); ], 500);
} }
// Login to vCenter first // Login to vCenter first
if (!$serviceVCenter->loginServer($vcenter)) { if (!$serviceVCenter->loginServer($vcenter)) {
return response()->json([ return response()->json([
@@ -1418,25 +1436,25 @@ Route::prefix('v1')
'message' => __('Cannot login to vCenter') 'message' => __('Cannot login to vCenter')
], 500); ], 500);
} }
$vmInfo = $serviceVCenter->GetDetailVirtualMachine($vm_id); $vmInfo = $serviceVCenter->GetDetailVirtualMachine($vm_id);
if ($vmInfo['error']) { if ($vmInfo['error']) {
return response()->json([ return response()->json([
'error' => true, 'error' => true,
'message' => __('Cannot get VM information from vCenter') 'message' => __('Cannot get VM information from vCenter')
], 500); ], 500);
} }
$vmData = $vmInfo['data']; $vmData = $vmInfo['data'];
// Parse các tham số được yêu cầu // Parse các tham số được yêu cầu
$requestedParams = []; $requestedParams = [];
if ($params) { if ($params) {
// Tách các param bằng dấu phẩy hoặc dấu + // Tách các param bằng dấu phẩy hoặc dấu +
$requestedParams = preg_split('/[,+]/', $params); $requestedParams = preg_split('/[,+]/', $params);
} }
// Mapping dữ liệu đầy đủ // Mapping dữ liệu đầy đủ
$allData = [ $allData = [
'vm_id' => $vm_id, 'vm_id' => $vm_id,
@@ -1454,7 +1472,7 @@ Route::prefix('v1')
'boot_type' => $vmData['boot']['type'] ?? '', 'boot_type' => $vmData['boot']['type'] ?? '',
'efi_legacy_boot' => $vmData['boot']['efi_legacy_boot'] ?? false, 'efi_legacy_boot' => $vmData['boot']['efi_legacy_boot'] ?? false,
]; ];
// Thêm thông tin disk // Thêm thông tin disk
if (isset($vmData['disks']) && !empty($vmData['disks'])) { if (isset($vmData['disks']) && !empty($vmData['disks'])) {
$firstDisk = $vmData['disks'][0] ?? null; $firstDisk = $vmData['disks'][0] ?? null;
@@ -1464,7 +1482,7 @@ Route::prefix('v1')
$allData['disk_type'] = $firstDisk['value']['type'] ?? ''; $allData['disk_type'] = $firstDisk['value']['type'] ?? '';
} }
} }
// Thêm thông tin network // Thêm thông tin network
if (isset($vmData['nics']) && !empty($vmData['nics'])) { if (isset($vmData['nics']) && !empty($vmData['nics'])) {
$firstNic = $vmData['nics'][0] ?? null; $firstNic = $vmData['nics'][0] ?? null;
@@ -1474,7 +1492,7 @@ Route::prefix('v1')
$allData['network_state'] = $firstNic['value']['state'] ?? ''; $allData['network_state'] = $firstNic['value']['state'] ?? '';
} }
} }
// Nếu không có params cụ thể, trả về tất cả // Nếu không có params cụ thể, trả về tất cả
if (empty($requestedParams)) { if (empty($requestedParams)) {
return response()->json([ return response()->json([
@@ -1483,7 +1501,7 @@ Route::prefix('v1')
'data' => $allData 'data' => $allData
]); ]);
} }
// Lọc chỉ những thông tin được yêu cầu // Lọc chỉ những thông tin được yêu cầu
$filteredData = []; $filteredData = [];
foreach ($requestedParams as $param) { foreach ($requestedParams as $param) {
@@ -1494,13 +1512,13 @@ Route::prefix('v1')
$filteredData[$param] = null; // Hoặc có thể bỏ qua $filteredData[$param] = null; // Hoặc có thể bỏ qua
} }
} }
return response()->json([ return response()->json([
'error' => false, 'error' => false,
'message' => __('Successfully retrieved VM information'), 'message' => __('Successfully retrieved VM information'),
'data' => $filteredData 'data' => $filteredData
]); ]);
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('❌ Lỗi khi lấy thông tin VM với params', [ Log::error('❌ Lỗi khi lấy thông tin VM với params', [
'vm_id' => $vm_id, 'vm_id' => $vm_id,
@@ -1508,7 +1526,7 @@ Route::prefix('v1')
'error' => $e->getMessage(), 'error' => $e->getMessage(),
'trace' => $e->getTraceAsString() 'trace' => $e->getTraceAsString()
]); ]);
return response()->json([ return response()->json([
'error' => true, 'error' => true,
'message' => __('System error: :error', ['error' => $e->getMessage()]) 'message' => __('System error: :error', ['error' => $e->getMessage()])
@@ -1516,5 +1534,5 @@ Route::prefix('v1')
} }
})->name('api.user.GetVMInfoWithParams'); })->name('api.user.GetVMInfoWithParams');
}); });
}); });