require 'erb' module Soaspec # Handles working with OAuth2 class OAuth2 attr_accessor :params # Count of tries to obtain access token attr_accessor :retry_count # @param [Hash] params Parameters to make OAuth request # @param [String] api_username Username to use which can be set by Soaspec::ExchangeHandler def initialize(params, api_username) raise 'client_id and client_secret not set' unless params[:client_id] && params[:client_secret] self.params = params params[:username] = api_username || ERB.new(params[:username]).result(binding) if params[:username] params[:security_token] = ERB.new(params[:security_token]).result(binding) if params[:security_token] params[:token_url] = ERB.new(params[:token_url]).result(binding) if params[:token_url] params[:password] = ERB.new(params[:password]).result(binding) if params[:password] Soaspec::SpecLogger.info request_message end # @return [Hash] Hash containing access token parameters def response response = RestClient.post(params[:token_url], payload, cache_control: 'no_cache', verify_ssl: false) rescue RestClient::Exception => error Soaspec::SpecLogger.info(["oauth_error: #{error.message}", "oauth_response: #{error.response}"]) self.retry_count += 1 sleep 0.1 # Wait if a bit before retying obtaining access token retry if retry_count < 3 raise error else Soaspec::SpecLogger.info(["response_headers: #{response.headers}", "response_body: #{response.body}"]) if Soaspec.debug_oauth? JSON.parse(response) end # @return [String] String to represent OAuth for logging logs def request_message if Soaspec.debug_oauth? "request_params: #{payload}" else params[:username] ? "User '#{params[:username]}'" : 'client_credentials' end end # @return [String] Password to use in OAuth request def password params[:security_token] ? (params[:password] + params[:security_token]) : params[:password] end # Payload to add to o-auth request dependent on params provided # @return [Hash] Payload for retrieving OAuth access token def payload payload = { client_id: params[:client_id], client_secret: params[:client_secret] } payload.merge(if params[:password] && params[:username] { grant_type: 'password', username: params[:username], password: password, multipart: true } else { grant_type: 'client_credentials' } end) end end end