Current_user in Phoenix controller passed to Plug

Uses this sample code as an authentication plug-in:

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 

So, I pass the current_user variable downstream through Plug.Conn.assign/3 . What is the best way to get this variable in a Phoenix controller? I do this (code below), but I'm sure there is a better way to do this.

 def index(conn, _) do user_id = conn.assigns.current_user.id end 
+7
elixir phoenix-framework
source share
1 answer

override action/2 and enter it:

 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 
+9
source share

All Articles