minty 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. checksums.yaml +4 -4
  2. data/Gemfile +4 -16
  3. data/Gemfile.lock +28 -208
  4. data/README.md +58 -57
  5. data/Rakefile +4 -27
  6. data/docs/DefaultApi.md +217 -0
  7. data/docs/RedirectUrl.md +18 -0
  8. data/git_push.sh +57 -0
  9. data/lib/minty/api/default_api.rb +210 -0
  10. data/lib/minty/api_client.rb +388 -0
  11. data/lib/minty/api_error.rb +53 -0
  12. data/lib/minty/configuration.rb +275 -0
  13. data/lib/minty/models/redirect_url.rb +216 -0
  14. data/lib/minty/version.rb +9 -3
  15. data/lib/minty.rb +33 -7
  16. data/minty.gemspec +19 -32
  17. data/pkg/minty-1.1.0.gem +0 -0
  18. data/publish_rubygem.sh +1 -1
  19. data/spec/api/default_api_spec.rb +65 -0
  20. data/spec/api_client_spec.rb +222 -0
  21. data/spec/configuration_spec.rb +38 -0
  22. data/spec/models/redirect_url_spec.rb +28 -0
  23. data/spec/spec_helper.rb +95 -63
  24. metadata +37 -292
  25. data/.bundle/config +0 -4
  26. data/.devcontainer/Dockerfile +0 -19
  27. data/.devcontainer/devcontainer.json +0 -37
  28. data/.env.example +0 -2
  29. data/.gemrelease +0 -2
  30. data/.github/PULL_REQUEST_TEMPLATE.md +0 -33
  31. data/.github/dependabot.yml +0 -10
  32. data/.github/stale.yml +0 -20
  33. data/.gitignore +0 -18
  34. data/.rspec +0 -3
  35. data/.rubocop.yml +0 -9
  36. data/CODE_OF_CONDUCT.md +0 -3
  37. data/DEPLOYMENT.md +0 -61
  38. data/DEVELOPMENT.md +0 -35
  39. data/EXAMPLES.md +0 -195
  40. data/Guardfile +0 -39
  41. data/LICENSE +0 -21
  42. data/Makefile +0 -5
  43. data/RUBYGEM.md +0 -9
  44. data/codecov.yml +0 -22
  45. data/lib/minty/algorithm.rb +0 -7
  46. data/lib/minty/api/authentication_endpoints.rb +0 -30
  47. data/lib/minty/api/v2.rb +0 -8
  48. data/lib/minty/client.rb +0 -7
  49. data/lib/minty/exception.rb +0 -50
  50. data/lib/minty/mixins/api_token_struct.rb +0 -4
  51. data/lib/minty/mixins/headers.rb +0 -19
  52. data/lib/minty/mixins/httpproxy.rb +0 -125
  53. data/lib/minty/mixins/initializer.rb +0 -38
  54. data/lib/minty/mixins/validation.rb +0 -113
  55. data/lib/minty/mixins.rb +0 -23
  56. data/lib/minty_client.rb +0 -4
  57. data/spec/integration/lib/minty/api/api_authentication_spec.rb +0 -122
  58. data/spec/integration/lib/minty/minty_client_spec.rb +0 -92
  59. data/spec/lib/minty/client_spec.rb +0 -223
  60. data/spec/lib/minty/mixins/httpproxy_spec.rb +0 -658
  61. data/spec/lib/minty/mixins/initializer_spec.rb +0 -121
  62. data/spec/lib/minty/mixins/token_management_spec.rb +0 -129
  63. data/spec/lib/minty/mixins/validation_spec.rb +0 -559
  64. data/spec/support/credentials.rb +0 -14
  65. data/spec/support/dummy_class.rb +0 -20
  66. data/spec/support/dummy_class_for_proxy.rb +0 -6
  67. data/spec/support/dummy_class_for_restclient.rb +0 -4
  68. data/spec/support/dummy_class_for_tokens.rb +0 -18
  69. data/spec/support/import_users.json +0 -13
  70. data/spec/support/stub_response.rb +0 -3
data/EXAMPLES.md DELETED
@@ -1,195 +0,0 @@
1
- # Examples using ruby
2
-
3
- ## Build a URL to Universal Login Page
4
-
5
- ```ruby
6
- require 'minty'
7
-
8
- client = MintyClient.new(
9
- client_id: ENV['AUTH0_RUBY_CLIENT_ID'],
10
- client_secret: ENV['AUTH0_RUBY_CLIENT_SECRET'],
11
- domain: ENV['AUTH0_RUBY_DOMAIN'],
12
- )
13
-
14
- client.authorize_url 'http://localhost:3000'
15
-
16
- > => #<URI::HTTPS https://YOUR_DOMAIN/authorize?client_id=YOUR_CLIENT_ID&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3000>
17
-
18
- ```
19
-
20
- ## Management API Client
21
-
22
- As a simple example of how to get started with the management API, we'll create an admin route to point to a list of all users from Minty:
23
-
24
- ```ruby
25
- # config/routes.rb
26
- Rails.application.routes.draw do
27
- # ...
28
- get 'admin/users', to: 'all_users#index'
29
- # ...
30
- end
31
- ```
32
-
33
- ... and a Controller to handle that route:
34
-
35
- ```ruby
36
- # app/controllers/all_users_controller.rb
37
- require 'minty'
38
-
39
- class AllUsersController < ApplicationController
40
- # Get all users from Minty with "minty" in their email.
41
- def index
42
- @params = {
43
- q: "email:*minty*",
44
- fields: 'email,user_id,name',
45
- include_fields: true,
46
- page: 0,
47
- per_page: 50
48
- }
49
- @users = minty_client.users @params
50
- end
51
-
52
- private
53
-
54
- # Setup the Minty API connection.
55
- def minty_client
56
- @minty_client ||= MintyClient.new(
57
- client_id: ENV['AUTH0_RUBY_CLIENT_ID'],
58
- client_secret: ENV['AUTH0_RUBY_CLIENT_SECRET'],
59
- domain: ENV['AUTH0_RUBY_DOMAIN'],
60
- api_version: 2,
61
- timeout: 15 # optional, defaults to 10
62
- )
63
- end
64
- end
65
- ```
66
-
67
- In this example, we're using environment variables to store the values needed to connect to Minty and authorize. The `token` used above is an API token for the Management API with the scopes required to perform a specific action (in this case `read:users`). These tokens can be [generated manually](https://minty.page/docs/api/management/v2/tokens#get-a-token-manually) using a test Application or with the [Application](https://manage.minty.page/#/applications) being used for your project.
68
-
69
- Finally, we'll add a view to display the results:
70
-
71
- ```ruby
72
- # app/views/all_users/index.html.erb
73
- <h1>Users</h1>
74
- <%= debug @params %>
75
- <%= debug @users %>
76
- ```
77
-
78
- This should show the parameters passed to the `users` method and a list of users that matched the query (or an empty array if none).
79
-
80
- ## Organizations
81
-
82
- [Organizations](https://minty.page/docs/organizations) is a set of features that provide better support for developers who build and maintain SaaS and Business-to-Business (B2B) applications.
83
-
84
- Note that Organizations is currently only available to customers on our Enterprise and Startup subscription plans.
85
-
86
- ### Logging in with an Organization
87
-
88
- Configure the Authentication API client and pass your Organization ID to the authorize url:
89
-
90
- ```ruby
91
- require 'minty'
92
-
93
- @minty_client ||= MintyClient.new(
94
- client_id: '{YOUR_APPLICATION_CLIENT_ID}',
95
- client_secret: '{YOUR_APPLICATION_CLIENT_SECRET}',
96
- domain: '{YOUR_TENANT}.minty.page',
97
- organization: "{YOUR_ORGANIZATION_ID}"
98
- )
99
-
100
- universal_login_url = @minty_client.authorization_url("https://{YOUR_APPLICATION_CALLBACK_URL}")
101
-
102
- # redirect_to universal_login_url
103
- ```
104
-
105
- ### Accepting user invitations
106
-
107
- Minty Organizations allow users to be invited using emailed links, which will direct a user back to your application. The URL the user will arrive at is based on your configured `Application Login URI`, which you can change from your Application's settings inside the Minty dashboard. When they arrive at this URL, a `invitation` and `organization` query parameters will be provided
108
-
109
- ```ruby
110
- require 'minty'
111
-
112
- @minty_client ||= MintyClient.new(
113
- client_id: '{YOUR_APPLICATION_CLIENT_ID}',
114
- client_secret: '{YOUR_APPLICATION_CLIENT_ID}',
115
- domain: '{YOUR_TENANT}.minty.page',
116
- organization: "{YOUR_ORGANIZATION_ID}"
117
- )
118
-
119
- universal_login_url = @minty_client.authorization_url("https://{YOUR_APPLICATION_CALLBACK_URL}", {
120
- organization: "{ORGANIZATION_QUERY_PARAM}", # You can override organization if needed
121
- invitation: "{INVITATION_QUERY_PARAM}"
122
- })
123
-
124
- # redirect_to universal_login_url
125
- ```
126
-
127
- ## ID Token Validation
128
-
129
- An ID token may be present in the credentials received after authentication. This token contains information associated with the user that has just logged in, provided the scope used contained `openid`. You can [read more about ID tokens here](https://minty.page/docs/tokens/concepts/id-tokens).
130
-
131
- Before accessing its contents, you must first validate the ID token to ensure it has not been tampered with and that it is meant for your application to consume. Use the `validate_id_token` method to do so:
132
-
133
- ```ruby
134
- begin
135
- @minty_client.validate_id_token 'YOUR_ID_TOKEN'
136
- rescue Minty::InvalidIdToken => e
137
- # In this case the ID Token contents should not be trusted
138
- end
139
- ```
140
-
141
- The method takes the following optional keyword parameters:
142
-
143
- | Parameter | Type | Description | Default value |
144
- | -------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
145
- | `algorithm` | `JWTAlgorithm` | The [signing algorithm](https://minty.page/docs/tokens/concepts/signing-algorithms) used by your Minty application. | `Minty::Algorithm::RS256` (using the [JWKS URL](https://minty.page/docs/tokens/concepts/jwks) of your **Minty Domain**) |
146
- | `leeway` | Integer | Number of seconds to account for clock skew when validating the `exp`, `iat` and `azp` claims. | `60` |
147
- | `nonce` | String | The `nonce` value you sent in the call to `/authorize`, if any. | `nil` |
148
- | `max_age` | Integer | The `max_age` value you sent in the call to `/authorize`, if any. | `nil` |
149
- | `issuer` | String | By default the `iss` claim will be checked against the URL of your **Minty Domain**. Use this parameter to override that. | `nil` |
150
- | `audience` | String | By default the `aud` claim will be compared to your **Minty Client ID**. Use this parameter to override that. | `nil` |
151
- | `organization` | String | By default the `org_id` claim will be compared to your **Organization ID**. Use this parameter to override that. | `nil` |
152
-
153
- You can check the signing algorithm value under **Advanced Settings > OAuth > JsonWebToken Signature Algorithm** in your Minty application settings panel. [We recommend](https://minty.page/docs/tokens/concepts/signing-algorithms#our-recommendation) that you make use of asymmetric signing algorithms like `RS256` instead of symmetric ones like `HS256`.
154
-
155
- ```ruby
156
- # HS256
157
-
158
- begin
159
- @minty_client.validate_id_token 'YOUR_ID_TOKEN', algorithm: Minty::Algorithm::HS256.secret('YOUR_SECRET')
160
- rescue Minty::InvalidIdToken => e
161
- # Handle error
162
- end
163
-
164
- # RS256 with a custom JWKS URL
165
-
166
- begin
167
- @minty_client.validate_id_token 'YOUR_ID_TOKEN', algorithm: Minty::Algorithm::RS256.jwks_url('YOUR_URL')
168
- rescue Minty::InvalidIdToken => e
169
- # Handle error
170
- end
171
- ```
172
-
173
- ### Organization ID Token Validation
174
-
175
- If an org_id claim is present in the Access Token, then the claim should be validated by the API to ensure that the value received is expected or known.
176
-
177
- In particular:
178
-
179
- - The issuer (iss) claim should be checked to ensure the token was issued by Minty
180
-
181
- - the org_id claim should be checked to ensure it is a value that is already known to the application. This could be validated against a known list of organization IDs, or perhaps checked in conjunction with the current request URL. e.g. the sub-domain may hint at what organization should be used to validate the Access Token.
182
-
183
- Normally, validating the issuer would be enough to ensure that the token was issued by Minty. In the case of organizations, additional checks should be made so that the organization within an Minty tenant is expected.
184
-
185
- If the claim cannot be validated, then the application should deem the token invalid.
186
-
187
- ```ruby
188
- begin
189
- @minty_client.validate_id_token 'YOUR_ID_TOKEN', organization: '{Expected org_id}'
190
- rescue Minty::InvalidIdToken => e
191
- # In this case the ID Token contents should not be trusted
192
- end
193
- ```
194
-
195
- For more information, please read [Work with Tokens and Organizations](https://minty.page/docs/organizations/using-tokens) on Minty Docs.
data/Guardfile DELETED
@@ -1,39 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- scope group: :unit_test
4
-
5
- group :unit_test do
6
- guard 'rspec', cmd:
7
- "bundle exec rspec -P \"spec/lib/minty/**/*#{ENV['PATTERN']}*_spec.rb\"--drb --format Fuubar --color" do
8
- # run every updated spec file
9
- watch(%r{^spec/.+_spec\.rb$})
10
- # run the lib specs when a file in lib/ changes
11
- watch(%r{^lib/(.+)\.rb$}) { 'spec' }
12
- # run all test for helper changes
13
- watch('spec/spec_helper.rb') { 'spec' }
14
- end
15
- end
16
-
17
- group :integration do
18
- guard 'rspec', cmd:
19
- "MODE=full bundle exec rspec -P \"spec/integration/**/*#{ENV['PATTERN']}*_spec.rb\" --drb --format Fuubar --color" do
20
- # run every updated spec file
21
- watch(%r{^spec/.+_spec\.rb$})
22
- # run the lib specs when a file in lib/ changes
23
- watch(%r{^lib/(.+)\.rb$}) { 'spec' }
24
- # run all test for helper changes
25
- watch('spec/spec_helper.rb') { 'spec' }
26
- end
27
- end
28
-
29
- group :full do
30
- guard 'rspec', cmd:
31
- 'MODE=full bundle exec rspec --drb --format Fuubar --color' do
32
- # run every updated spec file
33
- watch(%r{^spec/.+_spec\.rb$})
34
- # run the lib specs when a file in lib/ changes
35
- watch(%r{^lib/(.+)\.rb$}) { 'spec' }
36
- # run all test for helper changes
37
- watch('spec/spec_helper.rb') { 'spec' }
38
- end
39
- end
data/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- The MIT License (MIT)
2
-
3
- Copyright (c) 2015 Minty, Inc. <support@minty.page> (http://minty.page)
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
data/Makefile DELETED
@@ -1,5 +0,0 @@
1
- default: git
2
- git:
3
- git add -A
4
- git commit -m "Modified `git status --porcelain | grep 'M' | wc -l` file(s), Added `git status --porcelain | grep 'A' | wc -l` file(s), Removed `git status --porcelain | grep 'D' | wc -l` file(s)" -m "`git status --porcelain`"
5
- git push -u origin main
data/RUBYGEM.md DELETED
@@ -1,9 +0,0 @@
1
- # Publish the Gem on RubyGems.org
2
-
3
- To publish the gem set `RUBYGEMS_EMAIL` and `RUBYGEMS_PASSWORD` environment variables with your email and password from your RubyGems account respectively.
4
- Then run the following [Docker](https://docs.docker.com/engine/installation/) commands in the terminal to build and publish the gem.
5
-
6
- ```bash
7
- docker build -t minty-publish-rubygem .
8
- docker run --rm -e RUBYGEMS_EMAIL="$RUBYGEMS_EMAIL" -e RUBYGEMS_PASSWORD="$RUBYGEMS_PASSWORD" -it minty-publish-rubygem /bin/sh publish_rubygem.sh
9
- ```
data/codecov.yml DELETED
@@ -1,22 +0,0 @@
1
- coverage:
2
- precision: 2
3
- round: down
4
- range: "60...100"
5
- status:
6
- project:
7
- default:
8
- enabled: true
9
- target: auto
10
- threshold: 5%
11
- if_no_uploads: error
12
- patch:
13
- default:
14
- enabled: true
15
- target: 80%
16
- threshold: 30%
17
- if_no_uploads: error
18
- changes:
19
- default:
20
- enabled: true
21
- if_no_uploads: error
22
- comment: false
@@ -1,7 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Minty
4
- module Algorithm
5
- include Minty::Mixins::Validation::Algorithm
6
- end
7
- end
@@ -1,30 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require 'jwt'
4
-
5
- module Minty
6
- module Api
7
- module AuthenticationEndpoints
8
- def sign_in_url(client_id: @client_id, client_secret: @client_secret, organization: @organization)
9
- response = request_with_retry(:get, '/sign_in_url')
10
- response['redirect_url']
11
- end
12
-
13
- def sign_up_url(client_id: @client_id, client_secret: @client_secret, organization: @organization)
14
- response = request_with_retry(:get, '/sign_up_url')
15
- response['redirect_url']
16
- end
17
-
18
- def forgot_password_url(client_id: @client_id, client_secret: @client_secret, organization: @organization)
19
- response = request_with_retry(:get, '/forgot_password_url')
20
- response['redirect_url']
21
- end
22
-
23
- private
24
-
25
- def to_query(hash)
26
- hash.map { |k, v| "#{k}=#{CGI.escape(v)}" unless v.nil? }.reject(&:nil?).join('&')
27
- end
28
- end
29
- end
30
- end
data/lib/minty/api/v2.rb DELETED
@@ -1,8 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Minty
4
- module Api
5
- module V2
6
- end
7
- end
8
- end
data/lib/minty/client.rb DELETED
@@ -1,7 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Minty
4
- class Client
5
- include Minty::Mixins
6
- end
7
- end
@@ -1,50 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Minty
4
- class Exception < StandardError
5
- attr_reader :error_data
6
-
7
- def initialize(message, error_data = {})
8
- super(message)
9
- @error_data = error_data
10
- end
11
- end
12
-
13
- class HTTPError < Minty::Exception
14
- def headers
15
- error_data[:headers]
16
- end
17
-
18
- def http_code
19
- error_data[:code]
20
- end
21
- end
22
-
23
- class Unauthorized < Minty::HTTPError; end
24
- class NotFound < Minty::HTTPError; end
25
- class Unsupported < Minty::HTTPError; end
26
- class ServerError < Minty::HTTPError; end
27
- class BadRequest < Minty::HTTPError; end
28
- class RequestTimeout < Minty::Exception; end
29
- class MissingUserId < Minty::Exception; end
30
- class MissingClientId < Minty::Exception; end
31
- class MissingOrganizationId < Minty::Exception; end
32
- class MissingActionName < Minty::Exception; end
33
- class MissingActionId < Minty::Exception; end
34
- class MissingExecutionId < Minty::Exception; end
35
- class MissingTriggerId < Minty::Exception; end
36
- class MissingParameter < Minty::Exception; end
37
- class MissingVersionId < Minty::Exception; end
38
- class AccessDenied < Minty::HTTPError; end
39
- class InvalidParameter < Minty::Exception; end
40
- class InvalidCredentials < Minty::Exception; end
41
- class InvalidApiNamespace < Minty::Exception; end
42
-
43
- class RateLimitEncountered < Minty::HTTPError
44
- def reset
45
- Time.at(Integer(headers[:x_ratelimit_reset])).utc
46
- end
47
- end
48
-
49
- class InvalidIdToken < Minty::Exception; end
50
- end
@@ -1,4 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- Minty::ApiToken = Struct.new :token do
4
- end
@@ -1,19 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require 'json'
4
-
5
- module Minty
6
- module Mixins
7
- module Headers
8
- def client_headers(client_id, client_secret, application_id)
9
- {
10
- 'Content-Type' => 'application/json',
11
- 'Authorization' => "Bearer #{client_secret}",
12
- 'API-MINTY-CLIENT-ID' => client_id,
13
- 'API-MINTY-APPLICATION-ID' => application_id,
14
- 'Accept' => 'application/json'
15
- }
16
- end
17
- end
18
- end
19
- end
@@ -1,125 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require 'addressable/uri'
4
- require 'retryable'
5
- require_relative '../exception'
6
-
7
- module Minty
8
- module Mixins
9
- module HTTPProxy
10
- attr_accessor :headers, :base_uri, :timeout, :retry_count
11
-
12
- DEFAULT_RETRIES = 3
13
- MAX_ALLOWED_RETRIES = 10
14
- MAX_REQUEST_RETRY_JITTER = 250
15
- MAX_REQUEST_RETRY_DELAY = 1000
16
- MIN_REQUEST_RETRY_DELAY = 250
17
- BASE_DELAY = 100
18
-
19
- %i[get post post_file put patch delete delete_with_body].each do |method|
20
- define_method(method) do |uri, body = {}, extra_headers = {}|
21
- body = body.delete_if { |_, v| v.nil? }
22
- token = get_token
23
- authorization_header(token) unless token.nil?
24
- request_with_retry(method, uri, body, extra_headers)
25
- end
26
- end
27
-
28
- def retry_options
29
- sleep_timer = lambda do |attempt|
30
- wait = BASE_DELAY * (2**attempt - 1)
31
- wait += rand(wait + 1..wait + MAX_REQUEST_RETRY_JITTER)
32
- wait = [MAX_REQUEST_RETRY_DELAY, wait].min
33
- wait = [MIN_REQUEST_RETRY_DELAY, wait].max
34
- wait / 1000.to_f.round(2)
35
- end
36
-
37
- tries = 1 + [Integer(retry_count || DEFAULT_RETRIES), MAX_ALLOWED_RETRIES].min
38
-
39
- {
40
- tries: tries,
41
- sleep: sleep_timer,
42
- on: Minty::RateLimitEncountered
43
- }
44
- end
45
-
46
- def encode_uri(uri)
47
- path = base_uri ? Addressable::URI.new(path: uri).normalized_path : Addressable::URI.escape(uri)
48
- url(path)
49
- end
50
-
51
- def url(path)
52
- "#{base_uri}#{path}"
53
- end
54
-
55
- def add_headers(h = {})
56
- raise ArgumentError, 'Headers must be an object which responds to #to_hash' unless h.respond_to?(:to_hash)
57
-
58
- @headers ||= {}
59
- @headers.merge!(h.to_hash)
60
- end
61
-
62
- def safe_parse_json(body)
63
- JSON.parse(body.to_s)
64
- rescue JSON::ParserError
65
- body
66
- end
67
-
68
- def request_with_retry(method, uri, body = {}, extra_headers = {})
69
- Retryable.retryable(retry_options) do
70
- request(method, uri, body, extra_headers)
71
- end
72
- end
73
-
74
- def request(method, uri, body = {}, extra_headers = {})
75
- result = case method
76
- when :get
77
- @headers ||= {}
78
- get_headers = @headers.merge({ params: body }).merge(extra_headers)
79
- call(:get, encode_uri(uri), timeout, get_headers)
80
- when :delete
81
- @headers ||= {}
82
- delete_headers = @headers.merge({ params: body })
83
- call(:delete, encode_uri(uri), timeout, delete_headers)
84
- when :delete_with_body
85
- call(:delete, encode_uri(uri), timeout, headers, body.to_json)
86
- when :post_file
87
- body.merge!(multipart: true)
88
- post_file_headers = headers.slice(*headers.keys - ['Content-Type'])
89
- call(:post, encode_uri(uri), timeout, post_file_headers, body)
90
- else
91
- call(method, encode_uri(uri), timeout, headers, body.to_json)
92
- end
93
-
94
- case result.code
95
- when 200...226 then safe_parse_json(result.body)
96
- when 400 then raise Minty::BadRequest.new(result.body, code: result.code, headers: result.headers)
97
- when 401 then raise Minty::Unauthorized.new(result.body, code: result.code, headers: result.headers)
98
- when 403 then raise Minty::AccessDenied.new(result.body, code: result.code, headers: result.headers)
99
- when 404 then raise Minty::NotFound.new(result.body, code: result.code, headers: result.headers)
100
- when 429 then raise Minty::RateLimitEncountered.new(result.body, code: result.code,
101
- headers: result.headers)
102
- when 500 then raise Minty::ServerError.new(result.body, code: result.code, headers: result.headers)
103
- else raise Minty::Unsupported.new(result.body, code: result.code, headers: result.headers)
104
- end
105
- end
106
-
107
- def call(method, url, timeout, headers, body = nil)
108
- RestClient::Request.execute(
109
- method: method,
110
- url: url,
111
- timeout: timeout,
112
- headers: headers,
113
- payload: body
114
- )
115
- rescue RestClient::Exception => e
116
- case e
117
- when RestClient::RequestTimeout
118
- raise Minty::RequestTimeout, e.message
119
- else
120
- e.response
121
- end
122
- end
123
- end
124
- end
125
- end
@@ -1,38 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require 'json'
4
-
5
- module Minty
6
- module Mixins
7
- module Initializer
8
- def initialize(config)
9
- options = Hash[config.map { |(k, v)| [k.to_sym, v] }]
10
-
11
- @base_uri = base_url(options)
12
- @timeout = options[:timeout] || 10
13
- @retry_count = options[:retry_count]
14
-
15
- extend Minty::Api::AuthenticationEndpoints
16
-
17
- @client_id = options[:client_id]
18
- @client_secret = options[:client_secret]
19
- @application_id = options[:application_id]
20
- @organization = options[:organization]
21
- @headers = client_headers(@client_id, @client_secret, @application_id)
22
- end
23
-
24
- def self.included(klass)
25
- klass.send :prepend, Initializer
26
- end
27
-
28
- private
29
-
30
- def base_url(options)
31
- @domain = options[:domain] || options[:namespace]
32
- raise InvalidApiNamespace, 'API namespace must supply an API domain' if @domain.to_s.empty?
33
-
34
- "https://#{@domain}"
35
- end
36
- end
37
- end
38
- end