You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
59 lines
2.2 KiB
PHP
59 lines
2.2 KiB
PHP
<?php
|
|
namespace App\Services\Cloud;
|
|
|
|
use App\Models\CloudInstance;
|
|
use App\Models\User;
|
|
use App\Services\AdminPermission;
|
|
use App\Services\Auth;
|
|
|
|
final class CloudAccess
|
|
{
|
|
public static function actor(bool $withSession = true): array
|
|
{
|
|
$user = Auth::getUser();
|
|
if (!$user instanceof User || !$user->isLogin || (int) $user->enable !== 1) {
|
|
throw new CloudError('请先登录', 401);
|
|
}
|
|
$admin = (bool) $user->is_admin;
|
|
$manage = $admin && AdminPermission::isSuperAdmin();
|
|
return ['user_id' => (int) $user->id, 'is_admin' => $admin, 'is_super_admin' => $manage,
|
|
'can_manage' => $manage, 'session_id' => $withSession ? CloudSessionService::current($user) : ''];
|
|
}
|
|
|
|
public static function manage(array $actor): void
|
|
{
|
|
if (!($actor['is_super_admin'] ?? false) || !($actor['can_manage'] ?? false)) {
|
|
throw new CloudError('只有超级管理员可以修改全局虚拟化配置', 403);
|
|
}
|
|
}
|
|
|
|
public static function instance($id, array $actor, bool $write = false): CloudInstance
|
|
{
|
|
$query = CloudInstance::where('status', '<>', 'deleted');
|
|
$global = ($actor['is_admin'] ?? false) && ($actor['is_super_admin'] ?? false) && ($actor['can_manage'] ?? false);
|
|
if (!($actor['is_admin'] ?? false) || ($write && !$global)) {
|
|
$query->where('user_id', $actor['user_id']);
|
|
}
|
|
if (ctype_digit((string) $id)) {
|
|
$query->where('id', (int) $id);
|
|
} else {
|
|
$query->where('uuid', (string) $id);
|
|
}
|
|
$matches = $query->limit(2)->get();
|
|
if ($matches->count() !== 1) {
|
|
throw new CloudError('虚拟机不存在或无权访问', 404);
|
|
}
|
|
return $matches->first();
|
|
}
|
|
|
|
public static function vmActor(CloudInstance $instance, array $actor): array
|
|
{
|
|
$global = ($actor['is_admin'] ?? false) && ($actor['is_super_admin'] ?? false) && ($actor['can_manage'] ?? false);
|
|
if ((int) $instance->user_id !== (int) $actor['user_id'] && !$global) {
|
|
throw new CloudError('无权修改该虚拟机', 403);
|
|
}
|
|
$actor['can_manage'] = true;
|
|
return $actor;
|
|
}
|
|
}
|