Private channel authorization - one to one chat

264 Views Asked by At

I have chat rooms that for now are one-to-one chats between two users.

This is the channel without authorization

Broadcast::channel('chat.{roomId}', function ($user, $roomId) {
     return ['id' => $user->id, 'name' => $user->name];
});

This way it works, but I wanted to change it to something like this so it can check if you are either sender or receiver in the room otherwise you are not allowed.

Broadcast::channel('chat.{roomId}', function ($user, $roomId) {
      if ($user->canJoinRoom($roomId)) {
        return ['id' => $user->id, 'name' => $user->name];
      }
});

and this is the canJoinRoom method in the User's model

public function canJoinRoom($roomID) {
        $room = MessageRoom::findOrFail($roomID);

        if($room){
            if(auth()->user()->id == $room->user_id || auth()->user()->id == $room->receiver_id){
                return $this->room_id == $roomID;
            }else{
                return false;
            }
        }else {
            return false;
        }
    }

With that, I get broadcasting/auth 404 Not found, when I try to use the user's method and check additional stuff.

Also tried this way, but I still get broadcasting/auth 404 Not found.

if ($user->id === MessageRoom::findOrFail($roomId)->user_id || $user->id === MessageRoom::findOrFail($roomId)->receiver_id) {
        return ['id' => $user->id, 'name' => $user->name];
    }
0

There are 0 best solutions below