Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

current_user in Phoenix controller passed by Plug

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
like image 262
Nando Sousa Avatar asked Oct 22 '15 23:10

Nando Sousa


1 Answers

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
like image 154
Chris McCord Avatar answered Sep 26 '22 01:09

Chris McCord