Class: Soaspec::OAuth2

Inherits:
Object
  • Object
show all
Defined in:
lib/soaspec/o_auth2.rb

Overview

Handles working with OAuth2

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params_sent, api_username = nil) ⇒ OAuth2

Returns a new instance of OAuth2.

Parameters:

  • params_sent (Hash)

    Parameters to make OAuth request

  • api_username (String) (defaults to: nil)

    Username to use which can be set by Soaspec::ExchangeHandler

Options Hash (params_sent):

  • URL (token_url)

    to retrieve OAuth token from. @Note this can be set globally instead of here

  • Client (client_id)

    ID

  • Client (client_secret)

    Secret

  • Username (username)

    used in password grant

  • Password (password)

    used in password grant

  • Security (security_token)

    Token used in password grant

Raises:

  • (ArgumentError)


60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/soaspec/o_auth2.rb', line 60

def initialize(params_sent, api_username = nil)
  self.retry_count = 0 # No initial tries at getting access token
  params = params_sent.transform_keys_to_symbols
  params[:token_url] ||= Soaspec::OAuth2.token_url
  raise ArgumentError, 'client_id and client_secret not set' unless params[:client_id] && params[:client_secret]
  raise ArgumentError, 'token_url mandatory' unless params[:token_url]

  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]
end

Class Attribute Details

.access_tokensObject



27
28
29
# File 'lib/soaspec/o_auth2.rb', line 27

def access_tokens
  @access_tokens
end

.debug_oauth=(value) ⇒ Object (writeonly)

Specify whether to see params sent to and retrieved from oauth. This will put password in log file, only recommended for debugging



31
32
33
# File 'lib/soaspec/o_auth2.rb', line 31

def debug_oauth=(value)
  @debug_oauth = value
end

.instance_urlsObject

List of URLs to that define the instance of an application



29
30
31
# File 'lib/soaspec/o_auth2.rb', line 29

def instance_urls
  @instance_urls
end

.refresh_tokenObject

Values are:

* :always - (Default) Request token from token url every time it is needed
* :once - Request token once for the entire execution of the suite


25
26
27
# File 'lib/soaspec/o_auth2.rb', line 25

def refresh_token
  @refresh_token
end

.request_message=(value) ⇒ Boolean (writeonly)

Returns Whether to include request message describing OAuth (either full or simplified).

Returns:

  • (Boolean)

    Whether to include request message describing OAuth (either full or simplified)



33
34
35
# File 'lib/soaspec/o_auth2.rb', line 33

def request_message=(value)
  @request_message = value
end

.retry_limitInteger

Returns How many times to attempt to authenticate before raising exception.

Returns:

  • (Integer)

    How many times to attempt to authenticate before raising exception



35
36
37
# File 'lib/soaspec/o_auth2.rb', line 35

def retry_limit
  @retry_limit
end

.token_urlObject

Default token url used across entire suite



20
21
22
# File 'lib/soaspec/o_auth2.rb', line 20

def token_url
  @token_url
end

Instance Attribute Details

#paramsObject



48
49
50
# File 'lib/soaspec/o_auth2.rb', line 48

def params
  @params
end

#retry_countObject



50
51
52
# File 'lib/soaspec/o_auth2.rb', line 50

def retry_count
  @retry_count
end

Class Method Details

.debug_oauth?Boolean

Returns Whether to see params sent to & received from oauth URL.

Returns:

  • (Boolean)

    Whether to see params sent to & received from oauth URL



37
38
39
# File 'lib/soaspec/o_auth2.rb', line 37

def debug_oauth?
  @debug_oauth || false
end

.request_message?Boolean

Returns Whether to include request message describing OAuth (either full or simplified).

Returns:

  • (Boolean)

    Whether to include request message describing OAuth (either full or simplified)



42
43
44
# File 'lib/soaspec/o_auth2.rb', line 42

def request_message?
  @request_message
end

Instance Method Details

#access_tokenString

Returns Existing or new access token, dependent on refresh_token attribute.

Returns:

  • (String)

    Existing or new access token, dependent on refresh_token attribute



89
90
91
92
93
94
95
96
97
# File 'lib/soaspec/o_auth2.rb', line 89

def access_token
  Soaspec::SpecLogger.info request_message if self.class.request_message?
  case Soaspec::OAuth2.refresh_token
  when :once
    Soaspec::OAuth2.access_tokens[params] ||= response['access_token']
  else # Default is :always
    response['access_token']
  end
end

#debug_oauth?Boolean

Retrieve whether to debug oauth parameters based on global settings

Returns:

  • (Boolean)

    Whether to see params sent to & received from oauth URL



76
77
78
# File 'lib/soaspec/o_auth2.rb', line 76

def debug_oauth?
  self.class.debug_oauth?
end

#instance_urlString

Retrieve instance_url according to access token response. Some applications have a different instance It’s assumed this will be constant for a set of oauth parameters

Returns:

  • (String)

    Instance url



84
85
86
# File 'lib/soaspec/o_auth2.rb', line 84

def instance_url
  Soaspec::OAuth2.instance_urls[params] ||= response['instance_url']
end

#passwordString

Returns Password to use in OAuth request.

Returns:

  • (String)

    Password to use in OAuth request



124
125
126
# File 'lib/soaspec/o_auth2.rb', line 124

def password
  params[:security_token] ? (params[:password] + params[:security_token]) : params[:password]
end

#payloadHash

Payload to add to o-auth request dependent on params provided

Returns:

  • (Hash)

    Payload for retrieving OAuth access token



130
131
132
133
134
135
136
137
138
139
140
# File 'lib/soaspec/o_auth2.rb', line 130

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
                  }.merge multipart true
                else
                  { grant_type: 'client_credentials' }.merge multipart false
                end)
end

#request_messageString

Returns String to represent OAuth for logging logs.

Returns:

  • (String)

    String to represent OAuth for logging logs



115
116
117
118
119
120
121
# File 'lib/soaspec/o_auth2.rb', line 115

def request_message
  if debug_oauth?
    "request_params: #{payload}"
  else
    params[:username] ? "User '#{params[:username]}'" : 'client_credentials'
  end
end

#responseHash

Returns Hash containing access token parameters.

Returns:

  • (Hash)

    Hash containing access token parameters



100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/soaspec/o_auth2.rb', line 100

def response
  Soaspec::SpecLogger.info "using oauth_params: #{params}" if debug_oauth?
  response = RestClient.post(params[:token_url], payload, cache_control: 'no_cache', verify_ssl: false)
rescue RestClient::Exception => e
  Soaspec::SpecLogger.info(["oauth_error: #{e.message}", "oauth_response: #{e.response}"])
  self.retry_count += 1
  sleep 0.1 # Wait if a bit before retying obtaining access token
  retry if retry_count < self.class.retry_limit
  raise e
else
  Soaspec::SpecLogger.info(["response: \n  headers: #{response&.headers}\n  body: #{response}\n"]) if debug_oauth?
  JSON.parse(response)
end