Ash Authentication session management

Greetings once again you amazing developers!

A question about Ash Authentication (AA) before I try to roll my own implementation. I need to do cookie session authentication where each session is stored upon sign-in and all are deleted upon sign out (akin to phoenix gen auth). I see that I could do:

store_all_tokens? true
require_token_presence_for_authentication? true

but how would I go about removing all of the user’s tokens upon sign out with AA? I’ve tried to dig through the source, but all I see is revoke_bearer_tokens, which seems to only create a revocation, when I need the inverse. Is there a better way of implementing this with AA? Apologies if I’m missing something…

Thank you!

1 Like

Hi there.

You can define an action on your token resource that deletes the appropriate records. You can identify which records to destroy based on the contents of the subject field, which is a composite of the authentication resource’s subject_name and the primary key (eg: "user?id=abcd1234"). Thankfully we have AshAuthentication.user_to_subject/1 to help with that.

Since we don’t yet have bulk deletes, I would probably do something like this:

actions do
  # ...

  action :sign_out, :integer do
    argument :user, MyApp.User, allow_nil?: false

    run fn input, _ ->
      subject = AshAuthentication.user_to_subject(input.arguments.user)

      import Ecto.Query

      query = from t in MyApp.Token,
        where: t.subject == ^subject

      {count, _} = MyApp.Repo.delete_all(query)
      {:ok, count}
    end
  end
end

(I haven’t run this code, so I don’t know if it’s right, but hopefully gives you a hint what to do)

2 Likes