Cannot load current_user into eex

Hi all,

I am using the new version of guardian for authentication which I have configured it works fine the only problem is when I want to display the current logged in username in my header.html.eex layout i.e

<ul class="nav navbar-nav navbar-right">
       <li class="dropdown user-dropdown">
             <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><%= if @current_user do %>
                       <span></span>
                    <%= @current_user.firstname %>&nbsp&nbsp<img src="<%= Petronexus.ProfilePicture.url({@current_user.profile_pic, User}) || '/images/default.png' %> " style="width: 35px; height:35px; margin-right: 5px; border-radius: 50%;"><% end %>
                                        <ul class="dropdown-menu">
                                            <li class="greet">Hi,&nbsp<%= @current_user.firstname %></li>
                                        </ul>
                                    </li>
                                </ul>

I do get the error assign @current_user not available in eex template.

Here is my guardian plug to fetch the current user

defmodule Petronexus.SetCurrentUser do
  def init(opts), do: opts

  def call(conn, _opts) do
    user = Guardian.Plug.current_resource(conn)
    Plug.Conn.assign(conn, :current_user, user)
  end
end

which I have added into my router.ex as

pipeline :login_required do
    plug Petronexus.Auth.Pipeline
    plug Petronexus.Plug.SetCurrentUser
  end
1 Like

The assign would either be passed to your template from the Controller, or from the View that back your page. What does the render call in the controller look like?

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

You might probably use a conditional render of @current_user

if @current_user do
...
end

The fact is You try to render this in the header, but maybe not all actions has a current_user.

yeah am using a conditional

Sorry to ask the obvious, but are you actually using the pipeline in your router block?

1 Like

do you mean this part?

pipeline :login_required do
    plug Petronexus.Auth.Pipeline
    plug Petronexus.Plug.SetCurrentUser
end

Basically he is asking, if you have pipe_through :login_required somewhere.

1 Like

yes i have

scope “/”, PetronexusWeb do
pipe_through [:browser, :login_required]

oooh yeah my bad :see_no_evil: I have 2 scopes in my router so I had not passed :login_required to one of them that was the reason. Silly mistake, I should be careful next time

1 Like