Takes this code example as a Plug to handle authentication:
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'm passing the variable current_user
downstream via Plug.Conn.assign/3
. What's the best way to get this variable in a Phoenix controller? I'm doing this way (code below), but i'm sure that there's a better way to do that.
def index(conn, _) do
user_id = conn.assigns.current_user.id
end
override action/2
and inject 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With