I am trying to use phx.gen.auth with some but not ALL of my pages and I’m running into errors because I have to assign current user in mount … even on the page that doesn’t require authentication.
Here are the links that will straddle both authentication and non-authentication BUT they all share the same “mount”
# The first general link is under pipe_through :browser because it won't require authentication. I want anyone to be able to see the list of "groups."
live "/groups", GroupLive.Index, :index
# These links are under
pipe_through [:browser, :require_authenticated_user]
because these all need authentication.
live "/groups/new", GroupLive.Index, :new:
live "/groups/:id/edit", GroupLive.Index, :edit
live "/groups/:id", GroupLive.Show, :show
live "/groups/:id/show/edit", GroupLive.Show, :edit
I added the following in mount:
def mount(_params, session, socket) do
socket =
socket
|> assign(:groups, list_groups())
|> assign_current_user(session)
{:ok, socket}
end
Assign_current_user(socket, session) is defined in LiveHelpers:
def assign_current_user(socket, session) do
assign_new(
socket,
:current_user,
fn -> Users.get_user_by_session_token(session["user_token"])
end )
end
When I run http://localhost:4000/groups (the page that doesn’t require authentication), I get this error:
** (ArgumentError) nil given for `token`. comparison with nil is forbidden as it is unsafe. Instead write a query with is_nil/1, for example: is_nil(s.token)
So then I added this to mount:
if not is_nil(session["user_token"]) do
socket = assign_current_user(socket, session)
end
That made the “/groups” page available without logging in BUT I can still access the form_component and delete pages without logging in as well! ARG!!!
How do I straddle the two worlds where some pages force authentication and others don’t when they are ALL sharing the same “mount” function?