Redirect and sign out after deleting user account with LiveView

Hi guys,

when a user click to delete their account, I want them to sign out and redirect to root page. Usually, for signing out user, we use UserAuth.log_out_user() but that function requires conn, and I have a socket here as I’m using LiveView so I was wondering, how do I do this properly?

def handle_event("delete_account", _params, socket) do
    case Accounts.delete_account(socket.assigns.current_user) do
      {:ok, _changes} ->
        {:noreply,
          socket
          |> put_flash(:info, "Account deleted successfully.")
          
        }

      {:error, _changeset} ->
        {:noreply,
          socket
          |> put_flash(:error, "Failed to delete account.")
        }
    end
  end
<.modal
     :if={@live_action == :delete}
     id="delete-account-modal" show on_cancel={JS.patch(~p"/account/settings")}
      >
      <div class="">
        <.button phx-click="delete_account" phx-disable-with="Deleting...">Delete Account</.button>
     </div>
</.modal>
def log_out_user(conn) do
    user_token = get_session(conn, :user_token)
    user_token && Accounts.delete_user_session_token(user_token)

    if live_socket_id = get_session(conn, :live_socket_id) do
      MyApp.Endpoint.broadcast(live_socket_id, "disconnect", %{})
    end

    conn
    |> renew_session()
    |> delete_resp_cookie(@remember_me_cookie)
    |> redirect(to: ~p"/")
  end

Yes, you need to use a controller for this. You can’t manipulate http session data in a websocket—in this case, deleting the user session data. This is a websocket limitation, not a LiveView one, so there’s no way around it. You should have gotten a delete route with phx_gen_auth (for logging out), so you could base a delete_account route off of that one that also delete-deletes the account (dang overloaded terminology!)

1 Like

Here’s our code if it can help as an example:

2 Likes