2
votes

Channels have the authorized? function, and I would like to pass the generated local token when joining the channel so that I can verify user's role, like this:

const data = { token: localStorage.getItem('phoenixAuthToken') };
channel.join(data).receive('ok', (response) => {
            ...
            });
        });

However, in my channel setup, I don't seem to receive anything from client on join:

def join("settings", payload, socket) do
  IO.inspect(payload)
  if authorized?(payload) do
    {:ok, socket}
  else
    {:error, %{reason: "unauthorized"}}
  end
end

IO.inspect(payload) is just %{}. What I'm doing wrong here? Is it even possible to receive the message when joining the channel?

1
Try attaching the data when you call .channel(), e.g. channel = socket.channel("foo", { token: ... }) and then just do channel.join().Dogbert
@Dogbert Thanks man!! I was just passing it then the wrong way.Ilya

1 Answers

6
votes

The payload that join/3 receives is the one set in the second argument of .channel() in the JS client side, not the argument passed to .join(). So, on the client side, you should be doing something like:

const data = { token: localStorage.getItem('phoenixAuthToken') };
const channel = socket.channel("foo", data);
channel.join().receive(...);