0
votes

I'm writing a sample app to Phoenix framework. my authenticate.ex:

defmodule Myapp.Plug.Authenticate do
  import Plug.Conn
  import Myapp.Router.Helpers
  import Phoenix.Controller

  def init(default), do: default

  def call(conn, default) do
    current_user = get_session(conn, :current_user)
    if current_user do
      assign(conn, :current_user, current_user)
    else
      conn
        |> put_flash(:error, 'You need to be signed in to view this page')
        |> redirect(to: session_path(conn, :new))
    end
  end
end

there is a controller in which I do not require authentication for a single action:

defmodule Myapp.SharedLinkController do
  use Myapp.Web, :controller
  alias Myapp.SharedLink

  plug Myapp.Plug.Authenticate when action in [:new, :create]

...

end

it works, but the problem is that there is a menu display depends on whether the user is authorized or not:

<%= if Map.has_key?(@conn.assigns, :current_user) do %>
  <li>first</li>
<% else %>
  <li>second</li>
<% end %>

and it turns out that on the page action, which I do not require authentication, I get that a user is not authorized, even when it is authorized. how can I solve this problem?

1
"I get that a user is not authorized" you mean you get the flash and redirect or you get the wrong menu? - Dogbert
@Dogbert, I get the wrong menu - Marsel.V
What is the value of @conn.assigns[:current_user] when you're logged out? Try adding <%= inspect @conn.assigns[:current_user] %> and seeing the output. - Dogbert
Does this work: <%= if assigns[:current_user] do %>? - Dogbert
You should invoke halt/1 in call function after redirect to prevent further plugs downstream from being invoked. Also in your template you should be able to invoke <%= if @current_user do %> to check if user is authenticated or not. HIH - Ali Naqvi

1 Answers

1
votes

I would split the code in two steps - first attempting to authenticate the user, loading from the database and assigning to the connection - you can always run this one, and simply assign nil, a special guest user or nothing, whatever you prefer. The second would be enforcing the user is authenticated based on the assigns in the connection - this one would run only where you need to - like the plug you currently have.