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.
45 lines
2.0 KiB
PHP
45 lines
2.0 KiB
PHP
<?php
|
|
namespace App\Middleware;
|
|
|
|
use App\Services\AdminCsrf;
|
|
use App\Services\Auth;
|
|
use App\Services\Cloud\CloudAccess;
|
|
use App\Services\Cloud\CloudError;
|
|
|
|
final class CloudApi
|
|
{
|
|
public function __invoke($request, $response, $next)
|
|
{
|
|
try {
|
|
$path = (string) $request->getUri()->getPath();
|
|
// Billing, SSH keys and paginated instance snapshots are owned
|
|
// entirely by PHP and never call the private libvirt engine.
|
|
// Authenticating these routes must therefore not create a
|
|
// cloud_sessions row.
|
|
$databaseOnly = preg_match('#^/api/v1/invoices(?:/|$)#D', $path) === 1
|
|
|| preg_match('#^/api/v1/admin/billing(?:/|$)#D', $path) === 1
|
|
|| preg_match('#^/api/v1/ssh-keys(?:/|$)#D', $path) === 1
|
|
|| $path === '/api/v1/vms/page';
|
|
$actor = CloudAccess::actor(!$databaseOnly);
|
|
if (AdminCsrf::requiresProtection($request->getMethod())) {
|
|
if ($request->getHeaderLine('X-CSRF-Token') !== '') {
|
|
$request = $request->withHeader(AdminCsrf::HEADER_NAME, $request->getHeaderLine('X-CSRF-Token'));
|
|
}
|
|
if (!AdminCsrf::verify($request)) {
|
|
throw new CloudError('CSRF 校验失败,请刷新页面', 403);
|
|
}
|
|
}
|
|
return $next(
|
|
$request->withAttribute('cloud_actor', $actor)->withAttribute('auth_user', Auth::getUser()),
|
|
$response
|
|
);
|
|
} catch (CloudError $exception) {
|
|
return $response->withJson(['error' => $exception->getMessage(), 'detail' => $exception->getMessage()], $exception->httpStatus)
|
|
->withHeader('Cache-Control', 'no-store');
|
|
} catch (\Throwable $exception) {
|
|
error_log('Cloud API unavailable: ' . get_class($exception));
|
|
return $response->withJson(['error' => '虚拟化业务暂不可用'], 503)->withHeader('Cache-Control', 'no-store');
|
|
}
|
|
}
|
|
}
|