简体   繁体   中英

Extending Doorkeeper TokenResponse class

I need to extend Doorkeeper::OAuth::TokenResponse class because I want to add something to returned data. By default that class creates a return body like this:

{
  "access_token": "...",
  "token_type": "bearer",
  "expires_in": 7200,
  "refresh_token": "...",
  "scope": "some_scope"
}

I'd like to keep that and add a new field:

{
  "access_token": "...",
  "token_type": "bearer",
  "expires_in": 7200,
  "refresh_token": "...",
  "scope": "some_scope",
  "my_custom_field": 47
}

Can I do that without monkey patching TokenResponse class? If not, is there anything I can do to improve my current implementation (for better compatibility with new versions of Doorkeeper and etc.)? Here is my current implementation:

module Doorkeeper
  module OAuth
    class TokenResponse
      old_body = instance_method(:body)

      define_method(:body) do
        body = old_body.bind(self).()
        if self.token.scopes.include? 'some_scope'
          body[:my_custom_field] = 47
        end
        body
      end
    end
  end
end

I do have tests for that functionality so I will know if upgrading Doorkeeper gem breaks it.

Yes, you do not need to monkey patch. There are a few things you can try.

  1. Fork the gem and make changes in your fork, while making sure to update your fork when there is a change.

    1. Go to github and fork the Doorkeeper Gem: https://github.com/doorkeeper-gem/doorkeeper .
    2. If you're using a Gemfile for your Ruby project, be sure to point to your fork of the gem, eg

       gem 'doorkeeper', github: 'USERNAME/doorkeeper' 
  2. If the change in your fork with the custom field is generic enough, do a pull request, but chances are this won't work, since the hash is for an OAuth Token Response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM