Making current user available on the entire application?

Hey there, hope you’re having a great day.

I wonder what is the best approach to make my current user available in the entire application, so far, I’m assigning it directly from my controllers like so:

def index(conn, _params) do
    current_user = Guardian.Plug.current_resource(conn)
    render(conn, "index.html", current_user: current_user)
end

But, it’s a bit of a pain to do that everytime, should I create a plug and pipe through it?

Thanks!

2 Likes

Ah plug would be the right way to do this. To be clear, it would not be available to the “entire application”, rather you’d just be setting data on that particular conn struct. Each HTTP request is operating in a different erlang process all within the same applicatoin.

5 Likes

If I’m not wrong, Phoenix.Controller.render already put all conn.assigns visible to view. If Guardian.Plug.current_resource put current_user into there (not in private) its already working, if not, you can use a Plug to move from private to assign.

To be clear, into your controller

conn
|> assign(:current_user, Guardian.Plug.current_resource(conn))
|> render("index.html")

as a plug

def call(conn, _opts) do
  conn
  |> assign(:current_user, Guardian.Plug.current_resource(conn))  
end
4 Likes