Phoenix presence use list only for authorized users

Hello, i want to use phoenix presence to track the users of my application but i want updates to be submitted only to superusers. i.e i don’t want to allow everybody to see who’s online. I tried implementing this by following the tutorial and adding a check on the handle_info(:after_join) of my channel like this: phxcrd/lib/phxcrd_web/channels/room_channel.ex at master · spapas/phxcrd · GitHub

I.e i’ve added this check: if socket.assigns[:perms] |> Enum.member?("superuser"), do: push(socket, "presence_state", Presence.list(socket)) to only push updates to superusers.

Is this the correct way to do it ? It seems to be working (i.e non superusers don’t receive any updates) but is this enough? could f.e somebody query the channel for updates ? i’m not very familiar with channels :frowning:

TIA for any help!

1 Like

you’ll want to intercept the presence_diff message and add your conditional there as well…
https://hexdocs.pm/phoenix/Phoenix.Channel.html#intercept/1-examples

  intercept ["presence_diff"]

  def handle_out("presence_diff", msg, socket) do
    if socket.assigns[:perms] |> Enum.member?("superuser"), do: push(socket, "presence_diff", msg)
    {:noreply, socket}
  end
4 Likes

Thanks @outlog, you are right that it also sends “presence_diff” messages which need to be authorized.

Also another question, is there a way to listen to all messages in a channel? For example I can do channel.on("presence_diff", msg => console.log("Got message", msg) ) to listen for presence_diff messages. Is there a way to listen to everything?

TIA

This is my goto resource for customizing phoenix presence information propagation: https://medium.com/@alvinlindstam/phoenix-presence-for-social-networks-5fb67143f0ad

Intercepts work as well, but can become a bottleneck.

7 Likes

Hello @LostKobrakai thank you this is an excellent resource.

I’ll use the intercepts filtering for now since the number of users that would concurrently join my app won’t be that many but I’ll definitely keep the other things mentioned in the tutorial in mind for future reference!

1 Like

believe onMessage is the override that receives everything… - https://github.com/phoenixframework/phoenix/blob/master/assets/js/phoenix.js#L545 (note the return requirement of that function…)
but would probably warn against it… what are you trying to do?

1 Like

Yes the onMessage seems to be the one thank you so much!

I just wanted to use it for debugging, to make sure that there are no other messages that may be pushed to un-authorized clients (and that is the case after I add the proper authorization checks), so my problem is resolved.

BR,
Serafeim

1 Like

fyi: as an alternative… you can easily inspect all websocket messages in your browser’s developer tools…

2 Likes

Thank you very much; I didn’t know that!

2 Likes