I have this plug in my router pipeline to login an user using a magic link:
defmodule CoreWeb.Router.Plugs.LoginWithMagicToken do
alias Core.Marketplace.Accounts.User
import Plug.Conn
def init(opts), do: opts
def call(%{params: %{"magic_token" => token}, assigns: %{current_user: nil}} = conn, opts) do
case User.sign_in_with_magic_link(%{token: token}, load: :token) do
{:ok, user} ->
uri = Phoenix.Controller.current_path(conn)
conn
|> Plug.Conn.delete_session(:return_to)
|> AshAuthentication.Plug.Helpers.store_authentication_result({:ok, user}) # |> AshAuthentication.Plug.Helpers.store_in_session(user)
|> Phoenix.Controller.redirect(to: uri)
|> halt()
_ ->
conn
end
end
def call(conn, _opts), do: conn
end
Basically, if the current_user
is nil and there is a "magic_token"
param in the url, it will try to sign_in with the magic link and then store it in the connection.
The User.sign_in_with_magic_link
works fine, it will return the user based on the token. The issue is that I can’t make the user persist in the connection.
AFAIK, the store_authentication_result
or store_in_session
helper functions should do the trick, but it doesn’t seem to work, it will still have current_user
as nil
after the redirect.
This was working before, so I’m not sure if it was an Ash Authentication upgrade that broke it or something else.
Also, I think it is important to note that this code is ran in an iframe.