diff --git a/src/Channels/Channel.php b/src/Channels/Channel.php index fa5d8a7..218baa0 100644 --- a/src/Channels/Channel.php +++ b/src/Channels/Channel.php @@ -257,8 +257,8 @@ class Channel if (! hash_equals( hash_hmac('sha256', $signature, $connection->app->secret), - Str::after($payload->auth, ':')) - ) { + Str::after(optional($payload)->auth ?? ':', ':') + )) { throw new InvalidSignature; } } diff --git a/src/Services/WebsocketService.php b/src/Services/WebsocketService.php index 3b990c2..2a15e2c 100644 --- a/src/Services/WebsocketService.php +++ b/src/Services/WebsocketService.php @@ -20,10 +20,10 @@ class WebsocketService // ); } - function getTenantable(string $socketId) + function getAuth(string $socketId) { config(['cache.default' => 'file']); - return cache()->get('ws_socket_tenantable_' . $socketId); + return cache()->get('ws_socket_auth_' . $socketId); } public static function getChannelConnections(string $channelName) @@ -43,4 +43,34 @@ class WebsocketService config(['cache.default' => 'file']); return cache()->get('ws_connection_' . $socketId); } + + public static function getAuthedUsers() + { + config(['cache.default' => 'file']); + return cache()->get('ws_socket_authed_users') ?? []; + } + + public static function isUserConnected($userId) + { + config(['cache.default' => 'file']); + $authed_users = cache()->get('ws_socket_authed_users') ?? []; + $user_ids = array_values($authed_users); + + return in_array($userId, $user_ids); + } + + public static function getUserSocketIds($userId) + { + config(['cache.default' => 'file']); + $authed_users = cache()->get('ws_socket_authed_users') ?? []; + $socket_ids = []; + + foreach ($authed_users as $socket_id => $u_id) { + if ($u_id == $userId) { + $socket_ids[] = $socket_id; + } + } + + return $socket_ids; + } } diff --git a/src/Websocket/Handler.php b/src/Websocket/Handler.php index 595ceb0..cb8d8ad 100644 --- a/src/Websocket/Handler.php +++ b/src/Websocket/Handler.php @@ -191,7 +191,7 @@ class Handler implements MessageComponentInterface } cache()->forget( - 'ws_socket_tenantable_' . $connection->socketId, + 'ws_socket_auth_' . $connection->socketId, ); if (@$this->channel_connections[$channel]) { @@ -207,6 +207,10 @@ class Handler implements MessageComponentInterface 'ws_active_channels', array_keys($this->channel_connections) ); + + $authed_users = cache()->get('ws_socket_authed_users') ?? []; + unset($authed_users[$connection->socketId]); + cache()->forever('ws_socket_authed_users', $authed_users); } $this->channelManager @@ -458,6 +462,16 @@ class Handler implements MessageComponentInterface /** @var \App\Models\User */ $user = Auth::user(); $user->refresh(); + + cache()->forever( + 'ws_socket_auth_' . $connection->socketId, + $user, + ); + + + $authed_users = cache()->get('ws_socket_authed_users') ?? []; + $authed_users[$connection->socketId] = $user->id; + cache()->forever('ws_socket_authed_users', $authed_users); } }