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) response = begin connection.send(method, &block) rescue Footrest::HttpError::NotFound => e raise e unless connection.headers[:authorization].nil? # Reauthenticate and retry if authorization header is nil authenticate! connection.send(method, &block) rescue Footrest::HttpError::Unauthorized # Reauthenticate and retry authenticate! connection.send(method, &block) end Badgrcat::ApiArray.process_response(response, self) end # Override Footrest request for sending params in body as json def request_with_params_in_body(method, path, options) request(method) do |r| r.path = fullpath(path) r.body = options.to_json unless options.empty? end end def authenticate! connection.headers[:authorization] = nil auth_url = config[:auth_url] 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, auth_url, tok_params) authdata = authresp.body @refresh_token = authdata["refresh_token"].presence || @refresh_token connection.headers[:authorization] = "#{authdata['token_type']} #{authdata['access_token']}" # Set content type as application/json connection.headers['Content-Type'] = "application/json" end end end