Killing all socket connections for a user in Phoenix Framework

Sergio Tapia
sergiotapia
Published in
1 min readFeb 3, 2018

Sometimes you want to cut off all socket connections for a user in your application.

A specific scenario: You deactivate a user, and while you protect your APIs from deactivated users, that socket is still open and they can still receive live events being broadcasted.

If they refresh the page you’re fine, because that socket is protected against deactivated users.

But while that authenticated window is open, they can still get data.

Here’s how you can effectively kill all open socket connections for a user.

alias MyApp.Web.Endpointdef deactivate(conn, %{"id" => user_id}) do
with {:ok, _user} <- MyApp.deactivate(user_id) do
Endpoint.broadcast("user_socket:#{user_id}", "disconnect", %{})
json(conn, %{message: "User has been deactivated."})
else
_ -> not_found_error(conn)
end
end

Just broadcast that event from your controller and you’re all set.

Of course you should add some authentication and authorization to this. Can this user deactivate people? Can he only deactivate people within his organization? Can he deactivate himself (woah!)?

I hope this puts you on the right path, enjoy!

--

--