【问题标题】:Get conn assigns in channel for Phoenix Framework在 Phoenix 框架的频道中获取 conn 分配
【发布时间】:2017-05-29 20:54:38
【问题描述】:

我需要从我频道中的 conn.assigns 获取一些信息。例如:

def handle_in("save", params, socket) do
    values = Poison.decode!(params)

    current_user = conn.assigns.current_user
    changeset =
      current_user
      |> build_assoc(:posts)
      |> Post.changeset(values)

    case Repo.insert(changeset) do
      {:ok, _} ->
        {:reply, :ok, socket}
      {:error, reason} ->
        {:reply, {:error, %{:msg => reason}}, socket}
    end
  end

但是 conn 显然在这里不可用。我应该如何获得分配?

【问题讨论】:

    标签: phoenix-framework


    【解决方案1】:

    套接字有一个assigns,它反映了conn上的分配。

    如果要获取用户,则需要使用Phoenix.Token.sign/4函数,并在socket上连接时传递值。

    您的模板中有这样的内容:

    <%= tag :meta, name: "channel_token", content: Phoenix.Token.sign(@conn, "user", @current_user.id) %>
    

    这在你的 JS 中:

    const token = document.querySelector('meta[name=channel_token]').getAttribute('content');
    const socket = new Socket('/socket', {params: {token: token}});
    

    然后您可以像这样验证套接字中的令牌(取自the docs):

    defmodule MyApp.UserSocket do
      use Phoenix.Socket
    
      def connect(%{"token" => token}, socket) do
        # Max age of 2 weeks (1209600 seconds)
        case Phoenix.Token.verify(socket, "user", token, max_age: 1209600) do
          {:ok, user_id} ->
            socket = assign(socket, :user, Repo.get!(User, user_id))
            {:ok, socket}
          {:error, _} ->
            :error
        end
      end
    end 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-07
      • 1970-01-01
      • 2017-11-05
      • 2016-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多