game-village-politics-backend/app/Websocket/GameController.php

47 lines
1.5 KiB
PHP
Raw Permalink Normal View History

<?php
namespace App\Websocket;
use App\Game\GameRuleViolation;
use BlaxSoftware\LaravelWebSockets\Services\WebsocketService;
use BlaxSoftware\LaravelWebSockets\Websocket\Controller;
use Closure;
/**
* Base for the game's WS controllers: authed only, and a refused intent answers
* `<event>:error` with `{message, code}` so the client can translate the code.
* Lives outside Controllers/ so the resolver never maps an event to it.
*/
abstract class GameController extends Controller
{
public $need_auth = true;
/**
* The client sends its bearer token as `authtoken` with every message, which the
* package resolves through Sanctum for that message only. Remember the socket's
* user, so the server authenticates its next messages itself (`socket_<id>`) and
* the game:events worker can find the owner's sockets for pushes.
*/
public function booted()
{
$user = auth()->user();
$socketId = $this->connection->socketId ?? null;
if (! $user || ! $socketId) {
return;
}
cache()->put("socket_$socketId", ['id' => $user->id, 'type' => $user::class], now()->addDay());
if ((WebsocketService::getAuthedUsers()[$socketId] ?? null) !== $user->id) {
WebsocketService::setUserAuthed($socketId, $user);
}
}
protected function play(Closure $intent): mixed
{
try {
return $intent();
} catch (GameRuleViolation $e) {
return $this->error(['message' => $e->getMessage(), 'code' => $e->reason]);
}
}
}