Xboard/app/Http/Middleware/Server.php
2025-01-07 01:20:11 +08:00

58 lines
1.6 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use App\Exceptions\ApiException;
use App\Models\Server as ServerModel;
use App\Services\ServerService;
use Closure;
use Illuminate\Http\Request;
class Server
{
public function handle(Request $request, Closure $next, ?string $nodeType = null)
{
$this->validateRequest($request);
$serverInfo = ServerService::getServer(
$request->input('node_id'),
$request->input('node_type') ?? $nodeType
);
if (!$serverInfo) {
throw new ApiException('Server does not exist');
}
$request->merge(['node_info' => $serverInfo]);
return $next($request);
}
private function validateRequest(Request $request): void
{
$request->validate([
'token' => [
'string',
'required',
function ($attribute, $value, $fail) {
if ($value !== admin_setting('server_token')) {
$fail("Invalid {$attribute}");
}
},
],
'node_id' => 'required',
'node_type' => [
'required',
'nullable',
function ($attribute, $value, $fail) use ($request) {
if (!ServerModel::isValidType($value)) {
$fail("Invalid node type specified");
return;
}
$request->merge([$attribute => ServerModel::normalizeType($value)]);
},
]
]);
}
}