Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Elixir Phoenix控制器中的当前用户通过插头传递_Elixir_Phoenix Framework - Fatal编程技术网

Elixir Phoenix控制器中的当前用户通过插头传递

Elixir Phoenix控制器中的当前用户通过插头传递,elixir,phoenix-framework,Elixir,Phoenix Framework,将此代码示例作为处理身份验证的插件: defmodule Financeweb.APIAuth do ... def call(conn, _opts) do ... if authenticated_user do conn |> assign(:current_user, user) else conn |> send_resp(401, "{\"error\":\"unauthorized\"}")

将此代码示例作为处理身份验证的插件:

defmodule Financeweb.APIAuth do
...

  def call(conn, _opts) do
  ...

    if authenticated_user do
      conn
      |> assign(:current_user, user)
    else
      conn
      |> send_resp(401, "{\"error\":\"unauthorized\"}")
      |> halt
    end
  end
end
因此,我通过Plug.Conn.assign/3向下游传递变量
current\u user
。在Phoenix控制器中获取此变量的最佳方法是什么?我是这样做的(下面的代码),但我相信有更好的方法

def index(conn, _) do
  user_id = conn.assigns.current_user.id 
end

覆盖
操作/2
并将其注入:

def action(conn, _) do
  apply(__MODULE__, action_name(conn),
    [conn, conn.params, conn.assigns.current_user])
end

def index(conn, _params, current_user) do
  ...
end

def show(conn, _params, current_user) do
  ...
end