Phoenix 1.6.6
Phoenix Liveview 0.17.6
I have had issues with phx.gen.auth since upgrading to 1.6.6. I have a LiveView behind the :require_authenticated_user wall in my router. My understanding was that a redirect to this LiveView would go through the router and redirect first to login (which worked on 1.5). But that has not been happening on 1.6. Instead, the mount is called BEFORE a login is implemented and I get a run time error because the mount is assigning the current_user thinking that the login has already been forced.
So I read the Phoenix LiveView hexdox on “Security considerations of the LiveView.” It recommends implementing on_mount to implement the same verifications as the router.
So I implemented the on_mount EXACTLY like the hexdoc example.
NOTE TO WHOEVER MANAGES THIS HEXDOC: I am very new and inexperienced with Phoenix LiveView. It would be really really helpful if you could update the hexdoc to indicate that UserLiveAuth is NOT the same as UserAuth. I struggled for a day because I initially implemented on_mount in my existing UserAuth file thinking it was the same file but just named differently. I got numerous ambiguity compilation errors because functions like “redirect” are in both Phoenix.LiveView as well as Phoenix.Controller.
I finally figured out that I had to create a new file in MyAppWeb/controllers that was UserLiveAuth. I then implemented exactly what is in the hexdoc example. Here is the code:
defmodule MyAppWeb.UserLiveAuth do
import Phoenix.LiveView
alias MyAppWeb.Users
def on_mount(:default, _params, %{"user_id" => user_id} = _session, socket) do
socket = assign_new(socket, :current_user,
fn -> Users.get_user!(user_id)
end)
if socket.assigns.current_user.confirmed_at do
{:cont, socket}
else
{:halt, redirect(socket, to: "/users/log_in")}
end
end
end
In my LiveView, I added this (just like hexdoc example):
defmodule MyAppWeb.ResourceformLive.ManageResources do
use MyAppWeb, :live_view
on_mount MyAppWeb.UserLiveAuth
...
end
RUN TIME ERROR:
(FunctionClauseError) no function clause matching in MyAppWeb.UserLiveAuth.on_mount/4
Any help would be most appreciated.