Using phx.gen.auth - logging in confirmed_user

The phx.gen.auth module has been super helpful for both plug-and-play authentication in the application as well as learning through code.
This is what I found in user_auth.ex in the controller folder -

@doc """
  Used for routes that require the user to be authenticated.

  If you want to enforce the user email is confirmed before
  they use the application at all, here would be a good place.
  """
  def require_authenticated_user(conn, _opts) do
    if conn.assigns[:current_user] do
      conn
    else
      conn
      |> put_flash(:error, "You must log in to access this page.")
      |> maybe_store_return_to()
      |> redirect(to: Routes.user_session_path(conn, :new))
      |> halt()
    end
  end

Look at how beautifully it is documented that - this is a good place if you want to allow only confirmed users to login.
The above function is a plug - and - is using conn which is not available in LiveView. So, modifying the code here would mean it would work only for regular views. For a LiveView, should we duplicate the code? Or is there any best practice available?

Finally a question (I think) I know the answer to!

The answer is yes, you have to put any verification or initialization you want to do to the socket into the mount function. Alternatively, you can use the on_mount function to bundle up things you want done. More at link.

https://hexdocs.pm/phoenix_live_view/security-model.html#mounting-considerations

1 Like

Thanks @llama. I have seen this document earlier as well. My concern is - we have to right the same logic twice - once in the plug - and one more time in the on_mount hook.
I thought there might be a way in which you only write it at one place inside the phx.gen.auth generated files. For example in the login function - or - may be get_user_by_password in the accounts context. I wanted to know the best way or what is the general practice.