1
votes

I'm using this bundle to integrate Ratchet websocket into my Symfony2 project: https://github.com/GeniusesOfSymfony/WebSocketBundle

I'm working on a chat application. The problem I encountered is how do I restrict access to the chat to logged in users?

The websocket is based on the WAMP PubSub protocol. My subscribe method in the ChatTopic class looks like this:

public function onSubscribe(ConnectionInterface $connection, Topic $topic, WampRequest $request) {
    $email = $this->clientManipulator->getClient($connection)->getUsername();
    $user = $this->userRepository->getByEmail($email);
    $msg = array();
    $msg["type"] = "userJoined";
    $msg["displayName"] = $user->getDisplayName();
    $topic->broadcast(['msg' => json_encode($msg)]);
}

As you can see, I managed to get the user session inside my websocket and fetch all the user data from the db. I just don't know how to prevent unauthorized users from subscribing to the chat.

1
I think you could close the connection for that user using $connection->close(). - qooplmao

1 Answers

1
votes

Using $connection->close() is not reliable because client may reconnect and in that case would still be subscribed to the topic.

I would recommend you to use $topic->remove($conn). If you check the code on this link you will see that it actually removes the current $conn object from subscribers and therefore when broadcast() is called the message does not arrive to that client anymore.

The only issue is that client can still publish to this topic (although it cannot get the messages from this topic) but this can be prevented by adding the following condition in onPublish() method:

public function onPublish(\Ratchet\ConnectionInterface $conn, $topic, $event, array $exclude, array $eligible) {

if (!$topic->has($conn)) {

 // user is not allowed to publish to this channel - throw exception etc.

} else {

  // user is allowed to publish

  ...
  $topic->broadcast(...);
}
}