Quantcast
Channel: Design Bit
Viewing all articles
Browse latest Browse all 38

Killing all socket connections for a user in Phoenix Framework

$
0
0

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.Endpoint
def 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!


Killing all socket connections for a user in Phoenix Framework was originally published in sergiotapia on Medium, where people are continuing the conversation by highlighting and responding to this story.


Viewing all articles
Browse latest Browse all 38

Trending Articles