AshAuthentication Testing

Need help setting up a function that mocks a logged in user in my conn. I'm using magic link authentication, this is what I've got so far:
def log_in_user(conn, user) do
strategy = AshAuthentication.Info.strategy!(MyApp.Accounts.User, :magic_link)
{:ok, token} = AshAuthentication.Strategy.MagicLink.request_token_for(strategy, user)

conn
|> Phoenix.ConnTest.init_test_session(%{})
|> Plug.Conn.put_session(:user_token, token)
end
def log_in_user(conn, user) do
strategy = AshAuthentication.Info.strategy!(MyApp.Accounts.User, :magic_link)
{:ok, token} = AshAuthentication.Strategy.MagicLink.request_token_for(strategy, user)

conn
|> Phoenix.ConnTest.init_test_session(%{})
|> Plug.Conn.put_session(:user_token, token)
end
What's the correct way to go about this? Am I placing the wrong key in the session maybe? Does Ash have any helpers for this?
Solution:
```elixir def log_in_user(conn, user) do strategy = AshAuthentication.Info.strategy!(MyApp.Accounts.User, :magic_link) {:ok, token} = AshAuthentication.Strategy.MagicLink.request_token_for(strategy, user) user = Accounts.sign_in_with_magic_link!(%{token: token}, authorize?: false)...
Jump to solution
4 Replies
ZachDaniel
ZachDaniel4mo ago
I think something like that is the conventional way We've talked about having test helpers for it but no one has PRd anything yet 🥲
Joan Gavelán
Joan GavelánOP4mo ago
Oh. The thing is, it is not working 😅 How does Ash load the user from the session? Figured it out
Solution
Joan Gavelán
Joan Gavelán4mo ago
def log_in_user(conn, user) do
strategy = AshAuthentication.Info.strategy!(MyApp.Accounts.User, :magic_link)
{:ok, token} = AshAuthentication.Strategy.MagicLink.request_token_for(strategy, user)
user = Accounts.sign_in_with_magic_link!(%{token: token}, authorize?: false)

conn
|> Phoenix.ConnTest.init_test_session(%{})
|> AshAuthentication.Plug.Helpers.store_in_session(user)
end
def log_in_user(conn, user) do
strategy = AshAuthentication.Info.strategy!(MyApp.Accounts.User, :magic_link)
{:ok, token} = AshAuthentication.Strategy.MagicLink.request_token_for(strategy, user)
user = Accounts.sign_in_with_magic_link!(%{token: token}, authorize?: false)

conn
|> Phoenix.ConnTest.init_test_session(%{})
|> AshAuthentication.Plug.Helpers.store_in_session(user)
end
Joan Gavelán
Joan GavelánOP4mo ago
In case anyone needs it

Did you find this page helpful?