Access magic link token as string for testing

I'm trying to write a test where a user first requests a magic link and then uses the token to log in. How can I get the generated JWT token in clear text? When doing something like this I get a token struct:
test "It is possible to sign in with token" do
admin = generate(user(role: :admin))

{:ok, invited_user} =
Dreng.Accounts.invite_user(%{role: :farmer, email: "farmer@example.org"}, actor: admin)

token = get_magic_link_token(invited_user)

{:ok, signed_in_user} =
AshAuthentication.Info.strategy!(Dreng.Accounts.User, :magic_link_invite)
|> AshAuthentication.Strategy.action(:sign_in, %{token: token})

assert signed_in_user.id == invited_user.id
end
end

defp get_magic_link_token(%Dreng.Accounts.User{} = user) do
Dreng.Accounts.Token
|> Ash.Query.for_read(:read)
|> Ash.Query.filter(subject == ^"user?id=#{user.id}")
|> Ash.Query.filter(purpose == "magic_link")
|> Ash.read_one!(authorize?: false)
end
test "It is possible to sign in with token" do
admin = generate(user(role: :admin))

{:ok, invited_user} =
Dreng.Accounts.invite_user(%{role: :farmer, email: "farmer@example.org"}, actor: admin)

token = get_magic_link_token(invited_user)

{:ok, signed_in_user} =
AshAuthentication.Info.strategy!(Dreng.Accounts.User, :magic_link_invite)
|> AshAuthentication.Strategy.action(:sign_in, %{token: token})

assert signed_in_user.id == invited_user.id
end
end

defp get_magic_link_token(%Dreng.Accounts.User{} = user) do
Dreng.Accounts.Token
|> Ash.Query.for_read(:read)
|> Ash.Query.filter(subject == ^"user?id=#{user.id}")
|> Ash.Query.filter(purpose == "magic_link")
|> Ash.read_one!(authorize?: false)
end
Solution:
I've used the test mailer for this from swoosh
Jump to solution
4 Replies
EAJ
EAJOP3mo ago
I realize that right now this is "testing the framework", but in the future when I implement a custom auth page I'd like to test the whole flow
Solution
ZachDaniel
ZachDaniel3mo ago
I've used the test mailer for this from swoosh
ZachDaniel
ZachDaniel3mo ago
It will send your process the mail then you can pattern match it out
EAJ
EAJOP3mo ago
Was wondering if there was a cleaner way, but that should work. Thanks!

Did you find this page helpful?