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:

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…

  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}

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?


This is my goto resource for customizing phoenix presence information propagation:

Intercepts work as well, but can become a bottleneck.


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… - (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.


1 Like

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


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