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?
@conn.assigns[:current_user]when you're logged out? Try adding<%= inspect @conn.assigns[:current_user] %>and seeing the output. - Dogbert<%= if assigns[:current_user] do %>? - Dogbert<%= if @current_user do %>to check if user is authenticated or not. HIH - Ali Naqvi