chrismanderson
chrismanderson

Reputation: 4813

How to manually revoke a Doorkeeper token?

Say I have a user which I have soft-deleted from my system. I want to revoke their tokens as well. What's the best way of accomplishing this? Is it as simple as doing something like

Doorkeeper::AccessToken.where(resource_owner_id: deleted_user.id).each(&:revoke)

or is there a better approach?

Upvotes: 4

Views: 2171

Answers (2)

zhangyonguu
zhangyonguu

Reputation: 31

The answer of @Justin Workman is great.

After I checked the implement of revoke_all_for method

      def revoke_all_for(application_id, resource_owner, clock = Time)
        by_resource_owner(resource_owner)
          .where(
            application_id: application_id,
            revoked_at: nil,
          )
          .update_all(revoked_at: clock.now.utc)
      end

I found that if you want to revoke all tokens of a resource owner regardless of the application, you can just call:

Doorkeeper::AccessToken.by_resource_owner(resource_owner).where(revoked_at: nil).update_all(revoked_at: Time.now.utc)

We can save a db call which figure out all application_ids.

Upvotes: 0

Justin Workman
Justin Workman

Reputation: 698

You can do this, where application_id is a Doorkeeper application ID and resource_owner is the deleted user:

Doorkeeper::AccessToken.revoke_all_for(application_id, resource_owner)

Since you specifically asked about revoking all tokens for a user (without mentioning applications), your options are:

  1. Call it once per application ID you want to revoke (should be fine if you have very few application IDs), or
  2. Call it once, but pass an array of multiple application IDs instead of one (this method worked for me), or
  3. Modify the method to remove the scoping on application ID

Example of Method 2 that worked for me:

class User
  def revoke_all_access_tokens!
    application_ids = Doorkeeper::Application.pluck(:id) + [nil]
    Doorkeeper::AccessToken.revoke_all_for(application_ids, self)
  end
end

Note that + [nil] is necessary if you want to also delete tokens that don't have an application ID (depending on how you're using Doorkeeper).

The code for this method is small and easy to understand, if you need to customize it.

Upvotes: 1

Related Questions