docusign_monitor 1.0.0.pre.alpha

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,591 @@
1
+ =begin
2
+ #DocuSign Monitor API
3
+
4
+ #An API for an integrator to access the features of DocuSign Monitor
5
+
6
+ OpenAPI spec version: v2
7
+ Contact: devcenter@docusign.com
8
+ Generated by: https://github.com/swagger-api/swagger-codegen.git
9
+
10
+ =end
11
+
12
+ require 'date'
13
+ require 'json'
14
+ require 'logger'
15
+ require 'tempfile'
16
+ require 'typhoeus'
17
+ require 'uri'
18
+ require 'jwt'
19
+ require 'addressable/uri'
20
+
21
+ module DocuSign_Monitor
22
+ class ApiClient
23
+ # The Configuration object holding settings to be used in the API client.
24
+ attr_accessor :config
25
+
26
+ # Defines the headers to be used in HTTP requests of all API calls by default.
27
+ #
28
+ # @return [Hash]
29
+ attr_accessor :default_headers
30
+
31
+ attr_accessor :base_path
32
+ attr_accessor :oauth_base_path
33
+
34
+ # Initializes the ApiClient
35
+ # @option config [Configuration] Configuration for initializing the object, default to Configuration.default
36
+ def initialize(config = Configuration.default)
37
+ @config = config
38
+ @user_agent = "Swagger-Codegen/#{VERSION}/ruby"
39
+ @default_headers = {
40
+ 'Content-Type' => "application/json",
41
+ 'User-Agent' => @user_agent
42
+ }
43
+ end
44
+
45
+ def self.default
46
+ @@default ||= ApiClient.new
47
+ end
48
+
49
+ # Call an API with given options.
50
+ #
51
+ # @return [Array<(Object, Fixnum, Hash)>] an array of 3 elements:
52
+ # the data deserialized from response body (could be nil), response status code and response headers.
53
+ def call_api(http_method, path, opts = {})
54
+ request = build_request(http_method, path, opts)
55
+ response = request.run
56
+
57
+ if @config.debugging
58
+ @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
59
+ end
60
+
61
+ unless response.success?
62
+ if response.timed_out?
63
+ fail ApiError.new('Connection timed out')
64
+ elsif response.code == 0
65
+ # Errors from libcurl will be made visible here
66
+ fail ApiError.new(:code => 0,
67
+ :message => response.return_message)
68
+ else
69
+ fail ApiError.new(:code => response.code,
70
+ :response_headers => response.headers,
71
+ :response_body => response.body),
72
+ response.status_message
73
+ end
74
+ end
75
+
76
+ if opts[:return_type]
77
+ data = deserialize(response, opts[:return_type])
78
+ else
79
+ data = nil
80
+ end
81
+ return data, response.code, response.headers
82
+ end
83
+
84
+ # Builds the HTTP request
85
+ #
86
+ # @param [String] http_method HTTP method/verb (e.g. POST)
87
+ # @param [String] path URL path (e.g. /account/new)
88
+ # @option opts [Hash] :header_params Header parameters
89
+ # @option opts [Hash] :query_params Query parameters
90
+ # @option opts [Hash] :form_params Query parameters
91
+ # @option opts [Object] :body HTTP body (JSON/XML)
92
+ # @return [Typhoeus::Request] A Typhoeus Request
93
+ def build_request(http_method, path, opts = {})
94
+ url = build_request_url(path, opts)
95
+ http_method = http_method.to_sym.downcase
96
+
97
+ header_params = @default_headers.merge(opts[:header_params] || {})
98
+
99
+ # Add SDK default header
100
+ header_params.store("X-DocuSign-SDK", "Ruby")
101
+
102
+ query_params = opts[:query_params] || {}
103
+ form_params = opts[:form_params] || {}
104
+
105
+ update_params_for_auth! header_params, query_params, opts[:auth_names]
106
+
107
+ # set ssl_verifyhosts option based on @config.verify_ssl_host (true/false)
108
+ _verify_ssl_host = @config.verify_ssl_host ? 2 : 0
109
+
110
+ req_opts = {
111
+ :method => http_method,
112
+ :headers => header_params,
113
+ :params => query_params,
114
+ :params_encoding => @config.params_encoding,
115
+ :timeout => @config.timeout,
116
+ :ssl_verifypeer => @config.verify_ssl,
117
+ :ssl_verifyhost => _verify_ssl_host,
118
+ :sslcert => @config.cert_file,
119
+ :sslkey => @config.key_file,
120
+ :verbose => @config.debugging
121
+ }
122
+
123
+ # set custom cert, if provided
124
+ req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert
125
+
126
+ if [:post, :patch, :put, :delete].include?(http_method)
127
+ req_body = build_request_body(header_params, form_params, opts[:body])
128
+ req_opts.update :body => req_body
129
+ if @config.debugging
130
+ @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
131
+ end
132
+ end
133
+
134
+ Typhoeus::Request.new(url, req_opts)
135
+ end
136
+
137
+ # Check if the given MIME is a JSON MIME.
138
+ # JSON MIME examples:
139
+ # application/json
140
+ # application/json; charset=UTF8
141
+ # APPLICATION/JSON
142
+ # */*
143
+ # @param [String] mime MIME
144
+ # @return [Boolean] True if the MIME is application/json
145
+ def json_mime?(mime)
146
+ (mime == "*/*") || !(mime =~ /\Aapplication\/json(;.*)?\z/i).nil?
147
+ end
148
+
149
+ # Deserialize the response to the given return type.
150
+ #
151
+ # @param [Response] response HTTP response
152
+ # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
153
+ def deserialize(response, return_type)
154
+ body = response.body
155
+ return nil if body.nil? || body.empty?
156
+
157
+ # return response body directly for String return type
158
+ return body if return_type == 'String'
159
+
160
+ # handle file downloading - save response body into a tmp file and return the File instance
161
+ return download_file(response) if return_type == 'File'
162
+
163
+ # ensuring a default content type
164
+ content_type = response.headers['Content-Type'] || 'application/json'
165
+
166
+ fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
167
+
168
+ begin
169
+ data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
170
+ rescue JSON::ParserError => e
171
+ if %w(String Date DateTime).include?(return_type)
172
+ data = body
173
+ else
174
+ raise e
175
+ end
176
+ end
177
+
178
+ convert_to_type data, return_type
179
+ end
180
+
181
+ # Convert data to the given return type.
182
+ # @param [Object] data Data to be converted
183
+ # @param [String] return_type Return type
184
+ # @return [Mixed] Data in a particular type
185
+ def convert_to_type(data, return_type)
186
+ return nil if data.nil?
187
+ case return_type
188
+ when 'String'
189
+ data.to_s
190
+ when 'Integer'
191
+ data.to_i
192
+ when 'Float'
193
+ data.to_f
194
+ when 'BOOLEAN'
195
+ data == true
196
+ when 'DateTime'
197
+ # parse date time (expecting ISO 8601 format)
198
+ DateTime.parse data
199
+ when 'Date'
200
+ # parse date time (expecting ISO 8601 format)
201
+ Date.parse data
202
+ when 'Object'
203
+ # generic object (usually a Hash), return directly
204
+ data
205
+ when /\AArray<(.+)>\z/
206
+ # e.g. Array<Pet>
207
+ sub_type = $1
208
+ data.map {|item| convert_to_type(item, sub_type) }
209
+ when /\AHash\<String, (.+)\>\z/
210
+ # e.g. Hash<String, Integer>
211
+ sub_type = $1
212
+ {}.tap do |hash|
213
+ data.each {|k, v| hash[k] = convert_to_type(v, sub_type) }
214
+ end
215
+ else
216
+ # models, e.g. Pet
217
+ DocuSign_Monitor.const_get(return_type).new.tap do |model|
218
+ model.build_from_hash data
219
+ end
220
+ end
221
+ end
222
+
223
+ # Save response body into a file in (the defined) temporary folder, using the filename
224
+ # from the "Content-Disposition" header if provided, otherwise a random filename.
225
+ #
226
+ # @see Configuration#temp_folder_path
227
+ # @return [Tempfile] the file downloaded
228
+ def download_file(response)
229
+ content_disposition = response.headers['Content-Disposition']
230
+ if content_disposition and content_disposition =~ /filename=/i
231
+ filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
232
+ prefix = sanitize_filename(filename)
233
+ else
234
+ prefix = 'download-'
235
+ end
236
+ prefix = prefix + '-' unless prefix.end_with?('-')
237
+
238
+ tempfile = nil
239
+ encoding = response.body.encoding
240
+ Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) do |file|
241
+ file.write(response.body)
242
+ tempfile = file
243
+ end
244
+ @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
245
+ "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
246
+ "will be deleted automatically with GC. It's also recommended to delete the temp file "\
247
+ "explicitly with `tempfile.delete`"
248
+ tempfile
249
+ end
250
+
251
+ # Sanitize filename by removing path.
252
+ # e.g. ../../sun.gif becomes sun.gif
253
+ #
254
+ # @param [String] filename the filename to be sanitized
255
+ # @return [String] the sanitized filename
256
+ def sanitize_filename(filename)
257
+ filename.gsub(/.*[\/\\]/, '')
258
+ end
259
+
260
+ def build_request_url(path, opts)
261
+ # Add leading and trailing slashes to path
262
+ path = "/#{path}".gsub(/\/+/, '/')
263
+ return Addressable::URI.encode("https://" + self.get_oauth_base_path + path) if opts[:oauth]
264
+ URI.encode(@config.base_url + path) Addressable::URI.encode(@config.base_url + path)
265
+ end
266
+
267
+ # Builds the HTTP request body
268
+ #
269
+ # @param [Hash] header_params Header parameters
270
+ # @param [Hash] form_params Query parameters
271
+ # @param [Object] body HTTP body (JSON/XML)
272
+ # @return [String] HTTP body data in the form of string
273
+ def build_request_body(header_params, form_params, body)
274
+ # http form
275
+ if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
276
+ header_params['Content-Type'] == 'multipart/form-data'
277
+ data = {}
278
+ form_params.each do |key, value|
279
+ case value
280
+ when File, Array, nil
281
+ # let typhoeus handle File, Array and nil parameters
282
+ data[key] = value
283
+ else
284
+ data[key] = value.to_s
285
+ end
286
+ end
287
+ elsif body
288
+ data = body.is_a?(String) ? body : body.to_json
289
+ else
290
+ data = nil
291
+ end
292
+ data
293
+ end
294
+
295
+ # Update hearder and query params based on authentication settings.
296
+ #
297
+ # @param [Hash] header_params Header parameters
298
+ # @param [Hash] query_params Query parameters
299
+ # @param [String] auth_names Authentication scheme name
300
+ def update_params_for_auth!(header_params, query_params, auth_names)
301
+ Array(auth_names).each do |auth_name|
302
+ auth_setting = @config.auth_settings[auth_name]
303
+ next unless auth_setting
304
+ case auth_setting[:in]
305
+ when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
306
+ when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
307
+ else fail ArgumentError, 'Authentication token must be in `query` of `header`'
308
+ end
309
+ end
310
+ end
311
+
312
+ # Sets user agent in HTTP header
313
+ #
314
+ # @param [String] user_agent User agent (e.g. swagger-codegen/ruby/1.0.0)
315
+ def user_agent=(user_agent)
316
+ @user_agent = user_agent
317
+ @default_headers['User-Agent'] = @user_agent
318
+ end
319
+
320
+ # Return Accept header based on an array of accepts provided.
321
+ # @param [Array] accepts array for Accept
322
+ # @return [String] the Accept header (e.g. application/json)
323
+ def select_header_accept(accepts)
324
+ return nil if accepts.nil? || accepts.empty?
325
+ # use JSON when present, otherwise use all of the provided
326
+ json_accept = accepts.find { |s| json_mime?(s) }
327
+ return json_accept || accepts.join(',')
328
+ end
329
+
330
+ # Return Content-Type header based on an array of content types provided.
331
+ # @param [Array] content_types array for Content-Type
332
+ # @return [String] the Content-Type header (e.g. application/json)
333
+ def select_header_content_type(content_types)
334
+ # use application/json by default
335
+ return 'application/json' if content_types.nil? || content_types.empty?
336
+ # use JSON when present, otherwise use the first one
337
+ json_content_type = content_types.find { |s| json_mime?(s) }
338
+ return json_content_type || content_types.first
339
+ end
340
+
341
+ # Convert object (array, hash, object, etc) to JSON string.
342
+ # @param [Object] model object to be converted into JSON string
343
+ # @return [String] JSON string representation of the object
344
+ def object_to_http_body(model)
345
+ return model if model.nil? || model.is_a?(String)
346
+ local_body = nil
347
+ if model.is_a?(Array)
348
+ local_body = model.map{|m| object_to_hash(m) }
349
+ else
350
+ local_body = object_to_hash(model)
351
+ end
352
+ local_body.to_json
353
+ end
354
+
355
+ # Convert object(non-array) to hash.
356
+ # @param [Object] obj object to be converted into JSON string
357
+ # @return [String] JSON string representation of the object
358
+ def object_to_hash(obj)
359
+ if obj.respond_to?(:to_hash)
360
+ obj.to_hash
361
+ else
362
+ obj
363
+ end
364
+ end
365
+
366
+ # Build parameter value according to the given collection format.
367
+ # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
368
+ def build_collection_param(param, collection_format)
369
+ case collection_format
370
+ when :csv
371
+ param.join(',')
372
+ when :ssv
373
+ param.join(' ')
374
+ when :tsv
375
+ param.join("\t")
376
+ when :pipes
377
+ param.join('|')
378
+ when :multi
379
+ # return the array directly as typhoeus will handle it as expected
380
+ param
381
+ else
382
+ fail "unknown collection format: #{collection_format.inspect}"
383
+ end
384
+ end
385
+
386
+ # Helper method to set base_path
387
+ # @param [String] base_path
388
+ def set_base_path(base_path)
389
+ self.base_path = base_path
390
+ end
391
+
392
+ # Helper method to set oauth base path
393
+ # @param [String] oauth_base_path if passed nil it will determined from base_path
394
+ def set_oauth_base_path(oauth_base_path=nil)
395
+ self.oauth_base_path = oauth_base_path if oauth_base_path
396
+ return if self.oauth_base_path
397
+
398
+ # did we need this check as we can determine it from base path
399
+ #raise ArgumentError.new('oAuthBasePath cannot be empty') unless oauth_base_path
400
+
401
+ # Derive OAuth Base Path if not given
402
+ if self.base_path.start_with?("https://demo") or self.base_path.start_with?("http://demo")
403
+ self.oauth_base_path = OAuth::DEMO_OAUTH_BASE_PATH
404
+ elsif self.base_path.start_with?("https://stage") or self.base_path.start_with?("http://stage")
405
+ self.oauth_base_path = OAuth::STAGE_OAUTH_BASE_PATH
406
+ else
407
+ self.oauth_base_path = OAuth::PRODUCTION_OAUTH_BASE_PATH
408
+ end
409
+ end
410
+
411
+ # Helper method to get oauth base path
412
+ def get_oauth_base_path
413
+ if !self.oauth_base_path
414
+ self.set_oauth_base_path()
415
+ end
416
+
417
+ self.oauth_base_path
418
+ end
419
+
420
+ # Helper method to configure the OAuth accessCode/implicit flow parameters
421
+ # @param [String] client_id DocuSign OAuth Client Id(AKA Integrator Key)
422
+ # @param scopes The list of requested scopes. Client applications may be scoped to a limited set of system access.
423
+ # @param [String] redirect_uri This determines where to deliver the response containing the authorization code
424
+ # @param [String] response_type Determines the response type of the authorization request, NOTE: these response types are mutually exclusive for a client application. A public/native client application may only request a response type
425
+ # of "token". A private/trusted client application may only request a response type of "code".
426
+ # @param [String] state Allows for arbitrary state that may be useful to your application. The value in this parameter
427
+ # will be round-tripped along with the response so you can make sure it didn't change.
428
+ # @return [String]
429
+ def get_authorization_uri(client_id, scopes, redirect_uri, response_type, state=nil)
430
+ self.oauth_base_path ||= self.get_oauth_base_path
431
+
432
+ scopes = scopes.join(' ') if scopes.kind_of?(Array)
433
+ scopes = OAuth::SCOPE_SIGNATURE if scopes.empty?
434
+
435
+ uri = "https://%{base_path}/oauth/auth?response_type=%{response_type}&scope=%{scopes}&client_id=%{client_id}&redirect_uri=%{redirect_uri}"
436
+ uri += "&state=%{state}" if state
437
+ uri % {base_path: self.oauth_base_path, response_type:response_type, scopes: scopes, client_id: client_id, redirect_uri: redirect_uri, state: state}
438
+ end
439
+
440
+ # Request JWT User Token
441
+ # @param [String] client_id DocuSign OAuth Client Id(AKA Integrator Key)
442
+ # @param [String] user_id DocuSign user Id to be impersonated
443
+ # @param [String] private_key_or_filename the RSA private key
444
+ # @param [Number] expires_in number of seconds remaining before the JWT assertion is considered as invalid
445
+ # @param scopes The list of requested scopes. Client applications may be scoped to a limited set of system access.
446
+ # @return [OAuth::OAuthToken]
447
+ def request_jwt_user_token(client_id, user_id, private_key_or_filename, expires_in = 3600,scopes=OAuth::SCOPE_SIGNATURE)
448
+ raise ArgumentError.new('client_id cannot be empty') if client_id.empty?
449
+ raise ArgumentError.new('user_id cannot be empty') if user_id.empty?
450
+ raise ArgumentError.new('private_key_or_filename cannot be empty') if private_key_or_filename.empty?
451
+
452
+ scopes = scopes.join(' ') if scopes.kind_of?(Array)
453
+ scopes = OAuth::SCOPE_SIGNATURE if scopes.empty?
454
+ expires_in = 3600 if expires_in > 3600
455
+ now = Time.now.to_i
456
+ claim = {
457
+ "iss" => client_id,
458
+ "sub" => user_id,
459
+ "aud" => self.get_oauth_base_path,
460
+ "iat" => now,
461
+ "exp" => now + expires_in,
462
+ "scope"=> scopes
463
+ }
464
+
465
+ private_key = if private_key_or_filename.include?("-----BEGIN RSA PRIVATE KEY-----")
466
+ private_key_or_filename
467
+ else
468
+ File.read(private_key_or_filename)
469
+ end
470
+
471
+ private_key_bytes = OpenSSL::PKey::RSA.new private_key
472
+ token = JWT.encode claim, private_key_bytes, 'RS256'
473
+ params = {
474
+ :header_params => {"Content-Type" => "application/x-www-form-urlencoded"},
475
+ :form_params => {
476
+ "assertion" => token,
477
+ "grant_type" => OAuth::GRANT_TYPE_JWT
478
+ },
479
+ :return_type => 'OAuth::OAuthToken',
480
+ :oauth => true
481
+ }
482
+ data, status_code, headers = self.call_api("POST", "/oauth/token", params)
483
+
484
+
485
+ raise ApiError.new('Some error accrued during process') if data.nil?
486
+
487
+ self.set_default_header('Authorization', data.token_type + ' ' + data.access_token)
488
+ data
489
+ end
490
+
491
+ # Request JWT User Token
492
+ # @param [String] client_id DocuSign OAuth Client Id(AKA Integrator Key)
493
+ # @param [String] private_key_or_filename the RSA private key
494
+ # @param [Number] expires_in number of seconds remaining before the JWT assertion is considered as invalid
495
+ # @param scopes The list of requested scopes. Client applications may be scoped to a limited set of system access.
496
+ # @return [OAuth::OAuthToken]
497
+ def request_jwt_application_token(client_id, private_key_or_filename, expires_in = 3600,scopes=OAuth::SCOPE_SIGNATURE)
498
+ raise ArgumentError.new('client_id cannot be empty') if client_id.empty?
499
+ raise ArgumentError.new('private_key_or_filename cannot be empty') if private_key_or_filename.empty?
500
+
501
+ scopes = scopes.join(' ') if scopes.kind_of?(Array)
502
+ scopes = OAuth::SCOPE_SIGNATURE if scopes.empty?
503
+ expires_in = 3600 if expires_in > 3600
504
+ now = Time.now.to_i
505
+ claim = {
506
+ "iss" => client_id,
507
+ "aud" => self.get_oauth_base_path,
508
+ "iat" => now,
509
+ "exp" => now + expires_in,
510
+ "scope"=> scopes
511
+ }
512
+
513
+ private_key = if private_key_or_filename.include?("-----BEGIN RSA PRIVATE KEY-----")
514
+ private_key_or_filename
515
+ else
516
+ File.read(private_key_or_filename)
517
+ end
518
+
519
+ private_key_bytes = OpenSSL::PKey::RSA.new private_key
520
+ token = JWT.encode claim, private_key_bytes, 'RS256'
521
+ params = {
522
+ :header_params => {"Content-Type" => "application/x-www-form-urlencoded"},
523
+ :form_params => {
524
+ "assertion" => token,
525
+ "grant_type" => OAuth::GRANT_TYPE_JWT
526
+ },
527
+ :return_type => 'OAuth::OAuthToken',
528
+ :oauth => true
529
+ }
530
+ data, status_code, headers = self.call_api("POST", "/oauth/token", params)
531
+
532
+ raise ApiError.new('Some error accrued during process') if data.nil?
533
+
534
+ self.set_default_header('Authorization', data.token_type + ' ' + data.access_token)
535
+ data
536
+ end
537
+
538
+ # Get User Info method takes the accessToken to retrieve User Account Data.
539
+ # @param [String] access_token
540
+ # @return [OAuth::UserInfo]
541
+ def get_user_info(access_token)
542
+ raise ArgumentError.new('Cannot find a valid access token. Cannot find a valid access token.') if access_token.empty?
543
+
544
+ params = {
545
+ :header_params => {"Authorization" => 'Bearer ' + access_token},
546
+ :return_type => 'OAuth::UserInfo',
547
+ :oauth => true
548
+ }
549
+ data, status_code, headers = self.call_api("GET", '/oauth/userinfo', params)
550
+ data
551
+ end
552
+
553
+ # GenerateAccessToken will exchange the authorization code for an access token and refresh tokens.
554
+ # @param [String] client_id DocuSign OAuth Client Id(AKA Integrator Key)
555
+ # @param [String] client_secret The secret key you generated when you set up the integration in DocuSign Admin console.
556
+ # @param [String] code The authorization code
557
+ def generate_access_token(client_id, client_secret, code)
558
+ raise ArgumentError.new('client_id cannot be empty') if client_id.empty?
559
+ raise ArgumentError.new('client_secret cannot be empty') if client_secret.empty?
560
+ raise ArgumentError.new('code cannot be empty') if code.empty?
561
+
562
+ authcode = "Basic " + Base64.strict_encode64("#{client_id}:#{client_secret}")
563
+ params = {
564
+ :header_params => {
565
+ "Authorization" => authcode,
566
+ "Content-Type" => "application/x-www-form-urlencoded"
567
+ },
568
+ :form_params => {
569
+ "grant_type" => 'authorization_code',
570
+ "code" => code,
571
+ },
572
+ :return_type => 'OAuth::OAuthToken',
573
+ :oauth => true
574
+ }
575
+ data, status_code, headers = self.call_api("POST", '/oauth/token', params)
576
+ abort(data.inspect)
577
+
578
+ end
579
+
580
+ def set_access_token(token_obj)
581
+ self.default_headers['Authorization'] = token_obj.access_token
582
+ end
583
+
584
+ # Helper method to add default header params
585
+ # @param [String] header_name
586
+ # @param [String] header_value
587
+ def set_default_header(header_name, header_value)
588
+ @default_headers[header_name] = header_value
589
+ end
590
+ end
591
+ end