How to exclude some users during the broadcast?

How broadcast!to send a message to all users who subscribe to a topic, except for the sender, is it possible to exclude certain users? or send to a specific user?

I need users to click events on the channel, but only the admin user will receive messages, other users will not receive messages, but only send them.

I can solve this problem on the client side, just let users ignore the messages they receive through broadcast!and only the user messages received from the administrator, but how to solve this on the server side?

In short, join the channel, but can only read or send only?

0
source share
1 answer

If you store the user in a socket, as described in https://hexdocs.pm/phoenix/Phoenix.Token.html

defmodule MyApp.UserSocket do
  use Phoenix.Socket

  def connect(%{"token" => token}, socket) do
    case Phoenix.Token.verify(socket, "user", token, max_age: 1209600) do
      {:ok, user_id} ->
        socket = assign(socket, :user, Repo.get!(User, user_id))
        {:ok, socket}
      {:error, _} -> #...
    end
  end
end

Then you can check the admin status of admin in the function handle_outfor your channel described here :

defmodule HelloPhoenix.RoomChannel do
  intercept ["new_msg"]
  ...
  def handle_out("new_msg", payload, socket) do
    if socket.assigns.user.admin do
      push socket, "new_msg", payload
    end
    {:noreply, socket}
  end
end

Depending on the amount of messages and the number of administrators, you might think that there is a channel specific to the administrator for these events. This will prevent processes from sending messages to non-admin users, rather than simply ignoring them.

+1
source

All Articles