凤凰框架&通过康恩

时间:2016-06-07 19:23:18

标签: elixir phoenix-framework

我正在使用凤凰框架,所以:

我在/web/static/js/socket.js

上有以下代码
chatInput.on("keypress", event => {
  if (event.keyCode === 13) {
    channel.push("new_msg", {body: chatInput.val()}); //im want to pass @conn here
    chatInput.val("")
  }
});

和/ web / channels / room_channel:

use Phoenix.Channel
defmodule fooBar do
  def handle_in("new_msg", %{"body" => body}, socket) do #and get conn here
    broadcast! socket, "new_msg", %{body: body}
    {:noreply, socket}
  end
end

我需要在room_channel得到conn。我怎么能在socket.js传递它?

1 个答案:

答案 0 :(得分:5)

以下是适合您的解决方案。 在您的router.ex.You中放置一个用户令牌,如:

defp put_user_token(conn, _) do
  current_user = get_session(:current_user)
  user_id_token = Phoenix.Token.sign(conn, "user_id", current_user.id)
  conn |> assign(:user_id, user_id_token)
end

然后你可以插入你的管道:

pipeline :browser do
 ...
 plug :put_user_token
end

并确保将您的用户令牌放入app.html.eex:

<script>window.userToken = "<%= assigns[:user_id] %>"</script>

现在您可以在socket.js中检查您的套接字:

let socket = new Socket("/socket", {params: {token: window.userToken}})

并在您的user_socket.ex中。您可以使用套接字分配您的令牌:

def connect(%{"token" => user_id_token}, socket) do
    case Phoenix.Token.verify(socket, "user_id", user_id_token, max_age: 1209600) do
      {:ok, id} ->
        {:ok, assign(socket, :user_id, id)}
      {:error, reason} ->
        reason
    end
  end

最后在你的频道中:

def handle_info(:after_join, socket) do 
    push socket, "user_joined", %{message: "User #{socket.assigns.user_id} has joined"
    {:noreply, socket}
end