Path: blob/1.0-develop/app/Http/Controllers/Api/Client/Servers/WebsocketController.php
10280 views
<?php12namespace Pterodactyl\Http\Controllers\Api\Client\Servers;34use Carbon\CarbonImmutable;5use Pterodactyl\Models\Server;6use Illuminate\Http\JsonResponse;7use Pterodactyl\Models\Permission;8use Pterodactyl\Services\Nodes\NodeJWTService;9use Pterodactyl\Exceptions\Http\HttpForbiddenException;10use Pterodactyl\Http\Requests\Api\Client\ClientApiRequest;11use Pterodactyl\Services\Servers\GetUserPermissionsService;12use Pterodactyl\Http\Controllers\Api\Client\ClientApiController;1314class WebsocketController extends ClientApiController15{16/**17* WebsocketController constructor.18*/19public function __construct(20private NodeJWTService $jwtService,21private GetUserPermissionsService $permissionsService,22) {23parent::__construct();24}2526/**27* Generates a one-time token that is sent along in every websocket call to the Daemon.28* This is a signed JWT that the Daemon then uses to verify the user's identity, and29* allows us to continually renew this token and avoid users maintaining sessions wrongly,30* as well as ensure that user's only perform actions they're allowed to.31*/32public function __invoke(ClientApiRequest $request, Server $server): JsonResponse33{34$user = $request->user();35if ($user->cannot(Permission::ACTION_WEBSOCKET_CONNECT, $server)) {36throw new HttpForbiddenException('You do not have permission to connect to this server\'s websocket.');37}3839$permissions = $this->permissionsService->handle($server, $user);4041$node = $server->node;42if (!is_null($server->transfer)) {43// Check if the user has permissions to receive transfer logs.44if (!in_array('admin.websocket.transfer', $permissions)) {45throw new HttpForbiddenException('You do not have permission to view server transfer logs.');46}4748// Redirect the websocket request to the new node if the server has been archived.49if ($server->transfer->archived) {50$node = $server->transfer->newNode;51}52}5354$token = $this->jwtService55->setExpiresAt(CarbonImmutable::now()->addMinutes(10))56->setUser($request->user())57->setClaims([58'server_uuid' => $server->uuid,59'permissions' => $permissions,60])61->handle($node, $user->id . $server->uuid);6263$socket = str_replace(['https://', 'http://'], ['wss://', 'ws://'], $node->getConnectionAddress());6465return new JsonResponse([66'data' => [67'token' => $token->toString(),68'socket' => $socket . sprintf('/api/servers/%s/ws', $server->uuid),69],70]);71}72}737475