Assign to socket empty on join

Hello,

I’m currently experimenting with authenticated channels in Phoenix and I am having a weird issue. In the user_socket.ex file the connect function is as follows

def connect(%{"token" => token}, socket, _connect_info) do
    case Phoenix.Token.verify(socket, "key", token) do
      {:ok, user_id} ->
        socket = assign(socket, :user_id, user_id)
        IO.puts("+++++++++++++++=")
        IO.inspect(socket)
        {:ok, socket}

      {:error, _reason} ->
        :error
    end

    {:ok, socket}
  end

The socket.assigns does contain the user_id as expected. However, once the socket gets to the join function, the assigns is empty. In the join I add a new assign which does gets passed to the handle_in

def join("comments:" <> topic_id, _payload, socket) do
    IO.puts("------------------")
    IO.inspect(socket)

    {:ok, assign(socket, :test, "test")}
  end

Am I handling the connect incorrectly, or where am I likely to be going wrong?

That is because you have {:ok, socket} right after the case block in your connect/3 function. Which means you are not returning the result of the case block.

Looks like you forgot to remove that line.

def connect(%{"token" => token}, socket, _connect_info) do
  case Phoenix.Token.verify(socket, "key", token) do
    {:ok, user_id} ->
      socket = assign(socket, :user_id, user_id)
      IO.puts("+++++++++++++++=")
      IO.inspect(socket)
      {:ok, socket}

    {:error, _reason} ->
      :error
  end
end
2 Likes

All I can say to this is :man_facepalming:

Thanks for spotting that.

1 Like