team-alembic / ash_authentication_phoenix

Drop-in authentication support for Phoenix apps using AshAuthentication.
MIT License
60 stars 29 forks source link

The `on_mount` override on `sign_in_route` doesn't get the current user set #367

Closed sevenseacat closed 8 months ago

sevenseacat commented 8 months ago

The guide for Ash authentication w/ LiveView mentions:

You can also use this to prevent users from visiting the auto generated sign_in route: sign_in_route(on_mount: [{MyAppWeb.LiveUserAuth, :live_no_user}])

I've added this in my app:

sign_in_route register_path: "/register",
                  reset_path: "/reset",
                  on_mount: [{MyAppWeb.LiveUserAuth, :live_no_user}],
                  overrides: [MyAppWeb.AuthOverrides, AshAuthentication.Phoenix.Overrides.Default]

With the MyAppWeb.LiveUserAuth module -

defmodule MyAppWeb.LiveUserAuth do
  @moduledoc """
  Helpers for authenticating users in LiveViews.
  """

  import Phoenix.Component
  use MyAppWeb, :verified_routes

  # the rest of the functions 

  def on_mount(:live_no_user, _params, _session, socket) do
    dbg(socket.assigns)

    if socket.assigns[:current_user] do
      {:halt, Phoenix.LiveView.redirect(socket, to: ~p"/")}
    else
      {:cont, assign(socket, :current_user, nil)}
    end
  end
end

But current_user is never set in the socket.assigns, whether a user is logged in or not.

[(my_app 0.1.0) lib/my_app_web/live_user_auth.ex:30: MyAppWeb.LiveUserAuth.on_mount/4]
socket.assigns #=> %{flash: %{}, __changed__: %{}, live_action: :sign_in}

So a user can still visit the sign-in page, even when already signed in.

jimsynz commented 8 months ago

Do you have plug :load_from_session in your :browser pipeline?

sevenseacat commented 8 months ago

Yep! Just double checked

jimsynz commented 8 months ago

Okay that's super weird.