bb_oauth 1.0.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,378 @@
1
+ require 'date'
2
+ require 'json'
3
+ require 'logger'
4
+ require 'tempfile'
5
+ require 'typhoeus'
6
+ require 'uri'
7
+
8
+ module BancoBrasilClientCredentials
9
+ class ApiClient
10
+ # The Configuration object holding settings to be used in the API client.
11
+ attr_accessor :config
12
+
13
+ # Defines the headers to be used in HTTP requests of all API calls by default.
14
+ #
15
+ # @return [Hash]
16
+ attr_accessor :default_headers
17
+
18
+ # Initializes the ApiClient
19
+ # @option config [Configuration] Configuration for initializing the object, default to Configuration.default
20
+ def initialize(config = Configuration.default)
21
+ @config = config
22
+ @user_agent = "Swagger-Codegen/#{VERSION}/ruby"
23
+ @default_headers = {
24
+ 'Content-Type' => 'application/json',
25
+ 'User-Agent' => @user_agent
26
+ }
27
+ end
28
+
29
+ def self.default
30
+ @@default ||= ApiClient.new
31
+ end
32
+
33
+ # Call an API with given options.
34
+ #
35
+ # @return [Array<(Object, Integer, Hash)>] an array of 3 elements:
36
+ # the data deserialized from response body (could be nil), response status code and response headers.
37
+ def call_api(http_method, path, opts = {})
38
+ request = build_request(http_method, path, opts)
39
+ response = request.run
40
+
41
+ if @config.debugging
42
+ @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body.force_encoding('utf-8')}\n~END~\n"
43
+ end
44
+
45
+ unless response.success?
46
+ if response.timed_out?
47
+ fail ApiError.new('Connection timed out')
48
+ elsif response.code == 0
49
+ # Errors from libcurl will be made visible here
50
+ fail ApiError.new(:code => 0,
51
+ :message => response.return_message)
52
+ else
53
+ fail ApiError.new(:code => response.code,
54
+ :response_headers => response.headers,
55
+ :response_body => response.body.force_encoding('utf-8')),
56
+ response.status_message
57
+ end
58
+ end
59
+
60
+ if opts[:return_type]
61
+ data = deserialize(response, opts[:return_type])
62
+ else
63
+ data = nil
64
+ end
65
+
66
+ return data, response.code, response.headers
67
+ end
68
+
69
+ # Builds the HTTP request
70
+ #
71
+ # @param [String] http_method HTTP method/verb (e.g. POST)
72
+ # @param [String] path URL path (e.g. /account/new)
73
+ # @option opts [Hash] :header_params Header parameters
74
+ # @option opts [Hash] :query_params Query parameters
75
+ # @option opts [Hash] :form_params Query parameters
76
+ # @option opts [Object] :body HTTP body (JSON/XML)
77
+ # @return [Typhoeus::Request] A Typhoeus Request
78
+ def build_request(http_method, path, opts = {})
79
+ url = build_request_url(path)
80
+ http_method = http_method.to_sym.downcase
81
+
82
+ header_params = @default_headers.merge(opts[:header_params] || {})
83
+ query_params = opts[:query_params] || {}
84
+ form_params = opts[:form_params] || {}
85
+
86
+
87
+ # set ssl_verifyhosts option based on @config.verify_ssl_host (true/false)
88
+ _verify_ssl_host = @config.verify_ssl_host ? 2 : 0
89
+
90
+ req_opts = {
91
+ :method => http_method,
92
+ :headers => header_params,
93
+ :params => query_params,
94
+ :params_encoding => @config.params_encoding,
95
+ :timeout => @config.timeout,
96
+ :ssl_verifypeer => @config.verify_ssl,
97
+ :ssl_verifyhost => _verify_ssl_host,
98
+ :sslcert => @config.cert_file,
99
+ :sslkey => @config.key_file,
100
+ :verbose => @config.debugging
101
+ }
102
+
103
+ # set custom cert, if provided
104
+ req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert
105
+
106
+ if [:post, :patch, :put, :delete].include?(http_method)
107
+ req_body = build_request_body(header_params, form_params, opts[:body])
108
+ req_opts.update :body => req_body
109
+ if @config.debugging
110
+ @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
111
+ end
112
+ end
113
+ request = Typhoeus::Request.new(url, req_opts)
114
+ download_file(request) if opts[:return_type] == 'File'
115
+ request
116
+ end
117
+
118
+ # Builds the HTTP request body
119
+ #
120
+ # @param [Hash] header_params Header parameters
121
+ # @param [Hash] form_params Query parameters
122
+ # @param [Object] body HTTP body (JSON/XML)
123
+ # @return [String] HTTP body data in the form of string
124
+ def build_request_body(header_params, form_params, body)
125
+ # http form
126
+ if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
127
+ header_params['Content-Type'] == 'multipart/form-data'
128
+ data = {}
129
+ form_params.each do |key, value|
130
+ case value
131
+ when ::File, ::Array, nil
132
+ # let typhoeus handle File, Array and nil parameters
133
+ data[key] = value
134
+ else
135
+ data[key] = value.to_s
136
+ end
137
+ end
138
+ elsif body
139
+ data = body.is_a?(String) ? body : body.to_json
140
+ else
141
+ data = nil
142
+ end
143
+ data
144
+ end
145
+
146
+ # Check if the given MIME is a JSON MIME.
147
+ # JSON MIME examples:
148
+ # application/json
149
+ # application/json; charset=UTF8
150
+ # APPLICATION/JSON
151
+ # */*
152
+ # @param [String] mime MIME
153
+ # @return [Boolean] True if the MIME is application/json
154
+ def json_mime?(mime)
155
+ (mime == '*/*') || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
156
+ end
157
+
158
+ # Deserialize the response to the given return type.
159
+ #
160
+ # @param [Response] response HTTP response
161
+ # @param [String] return_type some examples: "User", "Array<User>", "Hash<String, Integer>"
162
+ def deserialize(response, return_type)
163
+ body = response.body
164
+
165
+ # handle file downloading - return the File instance processed in request callbacks
166
+ # note that response body is empty when the file is written in chunks in request on_body callback
167
+ return @tempfile if return_type == 'File'
168
+
169
+ return nil if body.nil? || body.empty?
170
+
171
+ # return response body directly for String return type
172
+ return body if return_type == 'String'
173
+
174
+ # ensuring a default content type
175
+ content_type = response.headers['Content-Type'] || 'application/json'
176
+
177
+ fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
178
+
179
+ begin
180
+ data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
181
+ rescue JSON::ParserError => e
182
+ if %w(String Date DateTime).include?(return_type)
183
+ data = body
184
+ else
185
+ raise e
186
+ end
187
+ end
188
+
189
+ convert_to_type data, return_type
190
+ end
191
+
192
+ # Convert data to the given return type.
193
+ # @param [Object] data Data to be converted
194
+ # @param [String] return_type Return type
195
+ # @return [Mixed] Data in a particular type
196
+ def convert_to_type(data, return_type)
197
+ return nil if data.nil?
198
+ case return_type
199
+ when 'String'
200
+ data.to_s
201
+ when 'Integer'
202
+ data.to_i
203
+ when 'Float'
204
+ data.to_f
205
+ when 'Boolean'
206
+ data == true
207
+ when 'DateTime'
208
+ # parse date time (expecting ISO 8601 format)
209
+ DateTime.parse data
210
+ when 'Date'
211
+ # parse date time (expecting ISO 8601 format)
212
+ Date.parse data
213
+ when 'Object'
214
+ # generic object (usually a Hash), return directly
215
+ data
216
+ when /\AArray<(.+)>\z/
217
+ # e.g. Array<Pet>
218
+ sub_type = $1
219
+ data.map { |item| convert_to_type(item, sub_type) }
220
+ when /\AHash\<String, (.+)\>\z/
221
+ # e.g. Hash<String, Integer>
222
+ sub_type = $1
223
+ {}.tap do |hash|
224
+ data.each { |k, v| hash[k] = convert_to_type(v, sub_type) }
225
+ end
226
+ else
227
+ # models, e.g. Pet
228
+ BancoBrasilClientCredentials.const_get(return_type).build_from_hash(data)
229
+ end
230
+ end
231
+
232
+ # Save response body into a file in (the defined) temporary folder, using the filename
233
+ # from the "Content-Disposition" header if provided, otherwise a random filename.
234
+ # The response body is written to the file in chunks in order to handle files which
235
+ # size is larger than maximum Ruby String or even larger than the maximum memory a Ruby
236
+ # process can use.
237
+ #
238
+ # @see Configuration#temp_folder_path
239
+ def download_file(request)
240
+ tempfile = nil
241
+ encoding = nil
242
+ request.on_headers do |response|
243
+ content_disposition = response.headers['Content-Disposition']
244
+ if content_disposition && content_disposition =~ /filename=/i
245
+ filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
246
+ prefix = sanitize_filename(filename)
247
+ else
248
+ prefix = 'download-'
249
+ end
250
+ prefix = prefix + '-' unless prefix.end_with?('-')
251
+ encoding = response.body.encoding
252
+ tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
253
+ @tempfile = tempfile
254
+ end
255
+ request.on_body do |chunk|
256
+ chunk.force_encoding(encoding)
257
+ tempfile.write(chunk)
258
+ end
259
+ request.on_complete do |_response|
260
+ if tempfile
261
+ tempfile.close
262
+ @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
263
+ "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
264
+ "will be deleted automatically with GC. It's also recommended to delete the temp file "\
265
+ "explicitly with `tempfile.delete`"
266
+ end
267
+ end
268
+ end
269
+
270
+ # Sanitize filename by removing path.
271
+ # e.g. ../../sun.gif becomes sun.gif
272
+ #
273
+ # @param [String] filename the filename to be sanitized
274
+ # @return [String] the sanitized filename
275
+ def sanitize_filename(filename)
276
+ filename.gsub(/.*[\/\\]/, '')
277
+ end
278
+
279
+ def build_request_url(path)
280
+ # Add leading and trailing slashes to path
281
+ path = "/#{path}".gsub(/\/+/, '/')
282
+ @config.base_url + path
283
+ end
284
+
285
+ # Update hearder and query params based on authentication settings.
286
+ #
287
+ # @param [Hash] header_params Header parameters
288
+ # @param [Hash] query_params Query parameters
289
+ # @param [String] auth_names Authentication scheme name
290
+ def update_params_for_auth!(header_params, query_params, auth_names)
291
+ Array(auth_names).each do |auth_name|
292
+ auth_setting = @config.auth_settings[auth_name]
293
+ next unless auth_setting
294
+ case auth_setting[:in]
295
+ when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
296
+ when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
297
+ else fail ArgumentError, 'Authentication token must be in `query` of `header`'
298
+ end
299
+ end
300
+ end
301
+
302
+ # Sets user agent in HTTP header
303
+ #
304
+ # @param [String] user_agent User agent (e.g. swagger-codegen/ruby/1.0.0)
305
+ def user_agent=(user_agent)
306
+ @user_agent = user_agent
307
+ @default_headers['User-Agent'] = @user_agent
308
+ end
309
+
310
+ # Return Accept header based on an array of accepts provided.
311
+ # @param [Array] accepts array for Accept
312
+ # @return [String] the Accept header (e.g. application/json)
313
+ def select_header_accept(accepts)
314
+ return nil if accepts.nil? || accepts.empty?
315
+ # use JSON when present, otherwise use all of the provided
316
+ json_accept = accepts.find { |s| json_mime?(s) }
317
+ json_accept || accepts.join(',')
318
+ end
319
+
320
+ # Return Content-Type header based on an array of content types provided.
321
+ # @param [Array] content_types array for Content-Type
322
+ # @return [String] the Content-Type header (e.g. application/json)
323
+ def select_header_content_type(content_types)
324
+ # use application/json by default
325
+ return 'application/json' if content_types.nil? || content_types.empty?
326
+ # use JSON when present, otherwise use the first one
327
+ json_content_type = content_types.find { |s| json_mime?(s) }
328
+ json_content_type || content_types.first
329
+ end
330
+
331
+ # Convert object (array, hash, object, etc) to JSON string.
332
+ # @param [Object] model object to be converted into JSON string
333
+ # @return [String] JSON string representation of the object
334
+ def object_to_http_body(model)
335
+ return model if model.nil? || model.is_a?(String)
336
+
337
+ local_body = nil
338
+ if model.is_a?(Array)
339
+ local_body = model.map { |m| object_to_hash(m) }
340
+ else
341
+ local_body = object_to_hash(model)
342
+ end
343
+
344
+ local_body.to_json
345
+ end
346
+
347
+ # Convert object(non-array) to hash.
348
+ # @param [Object] obj object to be converted into JSON string
349
+ # @return [String] JSON string representation of the object
350
+ def object_to_hash(obj)
351
+ if obj.respond_to?(:to_hash)
352
+ obj.to_hash
353
+ else
354
+ obj
355
+ end
356
+ end
357
+
358
+ # Build parameter value according to the given collection format.
359
+ # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
360
+ def build_collection_param(param, collection_format)
361
+ case collection_format
362
+ when :csv
363
+ param.join(',')
364
+ when :ssv
365
+ param.join(' ')
366
+ when :tsv
367
+ param.join("\t")
368
+ when :pipes
369
+ param.join('|')
370
+ when :multi
371
+ # return the array directly as typhoeus will handle it as expected
372
+ param
373
+ else
374
+ fail "unknown collection format: #{collection_format.inspect}"
375
+ end
376
+ end
377
+ end
378
+ end
@@ -0,0 +1,41 @@
1
+ module BancoBrasilClientCredentials
2
+ class ApiError < StandardError
3
+ attr_reader :code, :response_headers, :response_body
4
+
5
+ # Usage examples:
6
+ # ApiError.new
7
+ # ApiError.new("message")
8
+ # ApiError.new(:code => 500, :response_headers => {}, :response_body => "")
9
+ # ApiError.new(:code => 404, :message => "Not Found")
10
+ def initialize(arg = nil)
11
+ if arg.is_a? Hash
12
+ if arg.key?(:message) || arg.key?('message')
13
+ super(arg[:message] || arg['message'])
14
+ else
15
+ super arg
16
+ end
17
+
18
+ arg.each do |k, v|
19
+ instance_variable_set "@#{k}", v
20
+ end
21
+ else
22
+ super arg
23
+ end
24
+ end
25
+
26
+ # Override to_s to display a friendly error message
27
+ def to_s
28
+ message
29
+ end
30
+
31
+ def message
32
+ msg = @message || "Error message: the server returns an error"
33
+
34
+ msg += "\nHTTP status code: #{code}" if code
35
+ msg += "\nResponse headers: #{response_headers}" if response_headers
36
+ msg += "\nResponse body: #{response_body}" if response_body
37
+
38
+ msg
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,184 @@
1
+ module BancoBrasilClientCredentials
2
+ class Configuration
3
+ # Defines url scheme
4
+ attr_accessor :scheme
5
+
6
+ # Defines url host
7
+ attr_accessor :host
8
+
9
+ # Defines url base path
10
+ attr_accessor :base_path
11
+
12
+ # Defines API keys used with API Key authentications.
13
+ #
14
+ # @return [Hash] key: parameter name, value: parameter value (API key)
15
+ #
16
+ # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string)
17
+ # config.api_key['api_key'] = 'xxx'
18
+ attr_accessor :api_key
19
+
20
+ # Defines API key prefixes used with API Key authentications.
21
+ #
22
+ # @return [Hash] key: parameter name, value: API key prefix
23
+ #
24
+ # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers)
25
+ # config.api_key_prefix['api_key'] = 'Token'
26
+ attr_accessor :api_key_prefix
27
+
28
+ # Defines the username used with HTTP basic authentication.
29
+ #
30
+ # @return [String]
31
+ attr_accessor :username
32
+
33
+ # Defines the password used with HTTP basic authentication.
34
+ #
35
+ # @return [String]
36
+ attr_accessor :password
37
+
38
+ # Defines the access token (Bearer) used with OAuth2.
39
+ attr_accessor :access_token
40
+
41
+ # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response
42
+ # details will be logged with `logger.debug` (see the `logger` attribute).
43
+ # Default to false.
44
+ #
45
+ # @return [true, false]
46
+ attr_accessor :debugging
47
+
48
+ # Defines the logger used for debugging.
49
+ # Default to `Rails.logger` (when in Rails) or logging to STDOUT.
50
+ #
51
+ # @return [#debug]
52
+ attr_accessor :logger
53
+
54
+ # Defines the temporary folder to store downloaded files
55
+ # (for API endpoints that have file response).
56
+ # Default to use `Tempfile`.
57
+ #
58
+ # @return [String]
59
+ attr_accessor :temp_folder_path
60
+
61
+ # The time limit for HTTP request in seconds.
62
+ # Default to 0 (never times out).
63
+ attr_accessor :timeout
64
+
65
+ # Set this to false to skip client side validation in the operation.
66
+ # Default to true.
67
+ # @return [true, false]
68
+ attr_accessor :client_side_validation
69
+
70
+ ### TLS/SSL setting
71
+ # Set this to false to skip verifying SSL certificate when calling API from https server.
72
+ # Default to true.
73
+ #
74
+ # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
75
+ #
76
+ # @return [true, false]
77
+ attr_accessor :verify_ssl
78
+
79
+ ### TLS/SSL setting
80
+ # Set this to false to skip verifying SSL host name
81
+ # Default to true.
82
+ #
83
+ # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
84
+ #
85
+ # @return [true, false]
86
+ attr_accessor :verify_ssl_host
87
+
88
+ ### TLS/SSL setting
89
+ # Set this to customize the certificate file to verify the peer.
90
+ #
91
+ # @return [String] the path to the certificate file
92
+ #
93
+ # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code:
94
+ # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145
95
+ attr_accessor :ssl_ca_cert
96
+
97
+ ### TLS/SSL setting
98
+ # Client certificate file (for client certificate)
99
+ attr_accessor :cert_file
100
+
101
+ ### TLS/SSL setting
102
+ # Client private key file (for client certificate)
103
+ attr_accessor :key_file
104
+
105
+ # Set this to customize parameters encoding of array parameter with multi collectionFormat.
106
+ # Default to nil.
107
+ #
108
+ # @see The params_encoding option of Ethon. Related source code:
109
+ # https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96
110
+ attr_accessor :params_encoding
111
+
112
+ attr_accessor :inject_format
113
+
114
+ attr_accessor :force_ending_format
115
+
116
+ def initialize
117
+ @scheme = 'https'
118
+ @host = 'oauth.bb.com.br'
119
+ @base_path = ''
120
+ @api_key = {}
121
+ @api_key_prefix = {}
122
+ @timeout = 0
123
+ @client_side_validation = true
124
+ @verify_ssl = true
125
+ @verify_ssl_host = true
126
+ @params_encoding = nil
127
+ @cert_file = nil
128
+ @key_file = nil
129
+ @debugging = false
130
+ @inject_format = false
131
+ @force_ending_format = false
132
+ @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT)
133
+
134
+ yield(self) if block_given?
135
+ end
136
+
137
+ # The default Configuration object.
138
+ def self.default
139
+ @@default ||= Configuration.new
140
+ end
141
+
142
+ def configure
143
+ yield(self) if block_given?
144
+ end
145
+
146
+ def scheme=(scheme)
147
+ # remove :// from scheme
148
+ @scheme = scheme.sub(/:\/\//, '')
149
+ end
150
+
151
+ def host=(host)
152
+ # remove http(s):// and anything after a slash
153
+ @host = host.sub(/https?:\/\//, '').split('/').first
154
+ end
155
+
156
+ def base_path=(base_path)
157
+ # Add leading and trailing slashes to base_path
158
+ @base_path = "/#{base_path}".gsub(/\/+/, '/')
159
+ @base_path = '' if @base_path == '/'
160
+ end
161
+
162
+ def base_url
163
+ "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}".sub(/\/+\z/, '')
164
+ end
165
+
166
+ # Gets API key (with prefix if set).
167
+ # @param [String] param_name the parameter name of API key auth
168
+ def api_key_with_prefix(param_name)
169
+ return @api_key[param_name] unless @api_key_prefix[param_name]
170
+
171
+ "#{@api_key_prefix[param_name]} #{@api_key[param_name]}"
172
+ end
173
+
174
+ # Gets Basic Auth token string
175
+ def basic_auth_token
176
+ 'Basic ' + ["#{username}:#{password}"].pack('m').delete("\r\n")
177
+ end
178
+
179
+ # Returns Auth Settings hash for api client.
180
+ def auth_settings
181
+ {}
182
+ end
183
+ end
184
+ end