Sha256: e27476afad675ce892fa4d7438516be484e9da8cc49ee536785322223e64d540

Contents?: true

Size: 1.53 KB

Versions: 1

Compression:

Stored size: 1.53 KB

Contents

require 'footrest/client'

module Badgrcat
  class Client < Footrest::Client
    require 'badgrcat/api_array' # monkey patch

    Dir[File.join(__dir__, 'client', '*.rb')].each do |mod|
      mname = File.basename(mod, '.*').camelize
      require mod
      include "Badgrcat::Client::#{mname}".constantize
    end

    # Override Footrest request for ApiArray support
    def request(method, &block)
      begin
        response = connection.send(method, &block)
      rescue Footrest::HttpError::Unauthorized
        # Reauthenticate and retry
        authenticate!
        response = connection.send(method, &block)
      end

      Badgrcat::ApiArray.process_response(response, self)
    end

    def authenticate!
      connection.headers[:authorization] = nil

      tok_params = {
        scope: config[:scope],
        client_id: config[:client_id],
        client_secret: config[:client_secret],
        grant_type: config[:grant_type],
      }

      tok_params.reject! { |_k, v| v.nil? }

      if @refresh_token
        tok_params.merge!({
          grant_type: "refresh_token",
          refresh_token: @refresh_token,
        })
      else
        tok_params.merge!({
          username: config[:username],
          password: config[:password],
        })
      end

      authresp = connection.send(:post, "o/token", tok_params)
      authdata = authresp.body

      @refresh_token = authdata["refresh_token"].presence || @refresh_token
      connection.headers[:authorization] = "#{authdata['token_type']} #{authdata['access_token']}"
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
bearcat-1.5.29 lib/badgrcat/client.rb