simple_auth_sdk 0.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 4ae10e404c5adbf382daad661070e4913bffa3509e72133967a8fef979e15d2b
4
+ data.tar.gz: ac1e3a974bc3ca6f86c70c94ebaaba2eb45674062c56d0c895fec20a9ce3b5f1
5
+ SHA512:
6
+ metadata.gz: 4bc384565d15bf056d6daffe565205b9f97c4adae40119bfbdff7795332de2b5ba82d289fd7e50e00851598329bfe0217bf21ad8d61119002780ffe1e7cda425
7
+ data.tar.gz: 4af951dd806ff9f395407d6fd7e91c6ade0beb216cecb8099ca987e3224e0c0a40d6ac7253759624fb31bc06d91bf25e7229cae5a5109f7b797e6d5a546a6ec1
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,40 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.6
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: single_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: single_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 160
14
+
15
+ Metrics/MethodLength:
16
+ Max: 50
17
+
18
+ Metrics/ModuleLength:
19
+ Max: 200
20
+
21
+ Metrics/AbcSize:
22
+ Enabled: false
23
+
24
+ Metrics/PerceivedComplexity:
25
+ Max: 20
26
+
27
+ Metrics/CyclomaticComplexity:
28
+ Max: 20
29
+
30
+ Naming/MethodParameterName:
31
+ Enabled: false
32
+
33
+ Style/Documentation:
34
+ Enabled: false
35
+
36
+ Metrics/BlockLength:
37
+ Enabled: false
38
+
39
+ Metrics/ParameterLists:
40
+ Max: 10
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2024-08-08
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at mhukic@sondermind.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Muhidin Hukic
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
13
+ all 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
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,39 @@
1
+ # SimpleAuthSdk
2
+
3
+ Simple Auth SDK provides a simple authentication mechanism for your Ruby applications. It is designed to be easy to use and integrate with your existing applications. The gem depends on the Ruby Roda application [ADD LINK HERE] to provider authentication services.
4
+
5
+ Additionally the gem provider RBAC (Role Based Access Control) services to manage user roles and permissions in your application.
6
+
7
+ ## Installation
8
+
9
+ TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
10
+
11
+ Install the gem and add to the application's Gemfile by executing:
12
+
13
+ $ bundle add UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
14
+
15
+ If bundler is not being used to manage dependencies, install the gem by executing:
16
+
17
+ $ gem install UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
18
+
19
+ ## Usage
20
+
21
+ TODO: Write usage instructions here
22
+
23
+ ## Development
24
+
25
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
26
+
27
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
28
+
29
+ ## Contributing
30
+
31
+ Bug reports and pull requests are welcome on GitHub at https://github.com/hukic-m/simple_auth_sdk. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/simple_auth_sdk/blob/main/CODE_OF_CONDUCT.md).
32
+
33
+ ## License
34
+
35
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
36
+
37
+ ## Code of Conduct
38
+
39
+ Everyone interacting in the SimpleAuthSdk project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/simple_auth_sdk/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require 'rubocop/rake_task'
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SimpleAuthSdk
4
+ module API
5
+ # This module provides authentication endpoints.
6
+ # It includes methods for authenticating a user and creating a new user account.
7
+ module AuthenticationEndpoints
8
+ include SimpleAuthSdk::Mixins::HTTPProxy
9
+
10
+ DEFAULT_LOGIN_URL = '/v1/auth/login'
11
+ DEFAULT_CREATE_USER_PATH = '/v1/auth/create-account'
12
+
13
+ # Authenticates a user with the given credentials.
14
+ #
15
+ # @param login [String] The login (username or email) of the user.
16
+ # @param password [String] The password of the user.
17
+ # @param uri [String] The URI for the login endpoint (optional).
18
+ # @return [Hash, String] The response from the authentication request, parsed as JSON if possible.
19
+ #
20
+ # @example
21
+ # authenticate_user(login: 'user@example.com', password: 'password123')
22
+ def authenticate_user(login:, password:, uri: DEFAULT_LOGIN_URL, auth_headers: {})
23
+ request_with_retry(:post, uri, { login: login, password: password }, auth_headers)
24
+ end
25
+
26
+ # Creates a new user account with the given credentials.
27
+ #
28
+ # @param login [String] The login (username or email) of the new user.
29
+ # @param confirmed_login [String] Confirmation of the login.
30
+ # @param password [String] The password for the new user.
31
+ # @param confirmed_password [String] Confirmation of the password.
32
+ # @param uri [String] The URI for the create account endpoint (optional).
33
+ # @return [Hash, String] The response from the create account request, parsed as JSON if possible.
34
+ #
35
+ # @example
36
+ # create_user(login: 'user@example.com', confirmed_login: 'user@example.com', password: 'password123', confirmed_password: 'password123')
37
+ def create_user(login:, confirmed_login:, password:, confirmed_password:, uri: DEFAULT_CREATE_USER_PATH, auth_headers: {})
38
+ body = {
39
+ 'login': login,
40
+ 'login-confirm': confirmed_login,
41
+ 'password': password,
42
+ 'password-confirm': confirmed_password
43
+ }
44
+ request_with_retry(:post, uri, body, auth_headers)
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SimpleAuthSdk
4
+ class Configuration
5
+ attr_accessor :base_uri
6
+
7
+ def initialize
8
+ # No default value for base_uri
9
+ @base_uri = nil
10
+ end
11
+
12
+ # Validate that base_uri is set
13
+ def validate!
14
+ raise 'Base URI must be configured' if @base_uri.nil? || @base_uri.empty?
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,96 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SimpleAuthSdk
4
+ # Default exception in namespace of SimpleAuthSdk
5
+ # if you want to catch all exceptions, then you should use this one.
6
+ # Network exceptions are not included
7
+ class Exception < StandardError
8
+ attr_reader :error_data
9
+
10
+ def initialize(message, error_data = {})
11
+ super(message)
12
+ @error_data = error_data
13
+ end
14
+ end
15
+
16
+ # Parent for all exceptions that arise out of HTTP error responses.
17
+ class HTTPError < SimpleAuthSdk::Exception
18
+ def headers
19
+ error_data[:headers]
20
+ end
21
+
22
+ def http_code
23
+ error_data[:code]
24
+ end
25
+ end
26
+
27
+ # Exception for unauthorized requests, if you see it,
28
+ # probably Bearer Token is not set correctly
29
+ class Unauthorized < SimpleAuthSdk::HTTPError; end
30
+
31
+ # Exception for not found resource, you query for an
32
+ # nonexistent resource, or wrong path
33
+ class NotFound < SimpleAuthSdk::HTTPError; end
34
+
35
+ # Exception for unknown error
36
+ class Unsupported < SimpleAuthSdk::HTTPError; end
37
+
38
+ # Exception for server error
39
+ class ServerError < SimpleAuthSdk::HTTPError; end
40
+
41
+ # Exception for incorrect request, you've sent wrong params
42
+ class BadRequest < SimpleAuthSdk::HTTPError; end
43
+
44
+ # Exception for timeouts
45
+ class RequestTimeout < SimpleAuthSdk::Exception; end
46
+
47
+ # Exception for unset user_id, this might cause removal of
48
+ # all users, or other unexpected behaviour
49
+ class MissingUserId < SimpleAuthSdk::Exception; end
50
+
51
+ # Exception for unset client_id
52
+ class MissingClientId < SimpleAuthSdk::Exception; end
53
+
54
+ # Exception for unset organization_id
55
+ class MissingOrganizationId < SimpleAuthSdk::Exception; end
56
+
57
+ # Exception for unset trigger_id
58
+ class MissingTriggerId < SimpleAuthSdk::Exception; end
59
+
60
+ # Exception for unset action_name
61
+ class MissingActionName < SimpleAuthSdk::Exception; end
62
+
63
+ # Exception for unset action_id
64
+ class MissingActionId < SimpleAuthSdk::Exception; end
65
+
66
+ # Exception for unset execution_id
67
+ class MissingExecutionId < SimpleAuthSdk::Exception; end
68
+
69
+ # Exception for an unset parameter
70
+ class MissingParameter < SimpleAuthSdk::Exception; end
71
+
72
+ # Exception for unset version_id
73
+ class MissingVersionId < SimpleAuthSdk::Exception; end
74
+
75
+ # API v2 access denied
76
+ class AccessDenied < SimpleAuthSdk::HTTPError; end
77
+
78
+ # Invalid parameter passed, e.g. empty where ID is required
79
+ class InvalidParameter < SimpleAuthSdk::Exception; end
80
+
81
+ # Invalid JWT
82
+ class InvalidCredentials < SimpleAuthSdk::Exception; end
83
+
84
+ # Invalid API namespace
85
+ class InvalidApiNamespace < SimpleAuthSdk::Exception; end
86
+
87
+ # API rate-limiting encountered
88
+ class RateLimitEncountered < SimpleAuthSdk::HTTPError
89
+ def reset
90
+ Time.at(Integer(headers[:x_ratelimit_reset])).utc
91
+ end
92
+ end
93
+
94
+ # Invalid ID token
95
+ class InvalidIdToken < SimpleAuthSdk::Exception; end
96
+ end
@@ -0,0 +1,211 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'addressable/uri'
4
+ require 'retryable'
5
+ require_relative '../exception'
6
+ require 'json'
7
+ require 'rest-client'
8
+
9
+ module SimpleAuthSdk
10
+ module Mixins
11
+ # HTTPProxy module provides methods for making HTTP requests using the rest-client gem.
12
+ # It includes functionality for retrying requests, encoding URIs, and handling various HTTP methods.
13
+ # You can integrate this module into your classes to easily make HTTP requests with retry logic.
14
+ module HTTPProxy
15
+ # @!attribute [rw] headers
16
+ # @return [Hash] the headers to be sent with each request.
17
+ attr_writer :headers
18
+
19
+ # @!attribute [rw] timeout
20
+ # @return [Integer] the timeout in seconds for HTTP requests.
21
+ attr_accessor :timeout
22
+
23
+ # @!attribute [rw] retry_count
24
+ # @return [Integer] the number of retries for failed requests.
25
+ attr_accessor :retry_count
26
+
27
+ DEFAULT_RETRIES = 3
28
+ MAX_ALLOWED_RETRIES = 10
29
+ MAX_REQUEST_RETRY_JITTER = 250
30
+ MAX_REQUEST_RETRY_DELAY = 1000
31
+ MIN_REQUEST_RETRY_DELAY = 250
32
+ BASE_DELAY = 100
33
+
34
+ # Defines HTTP methods that will be proxied to HTTP class methods.
35
+ # These methods will make an HTTP request with the corresponding HTTP method.
36
+ #
37
+ # @param auth_token [String, nil] the authentication token to be used for the request. If nil, no Authorization header is set.
38
+ # @param uri [String] the URI to make the request to.
39
+ # @param body [Hash] the request body.
40
+ # @param extra_headers [Hash] additional headers for the request.
41
+ # @return [Hash, String] the parsed response body, or raw response if JSON parsing fails.
42
+ %i[get post put patch delete delete_with_body].each do |method|
43
+ define_method(method) do |uri, auth_token = nil, body = {}, extra_headers = {}|
44
+ body = body.delete_if { |_, v| v.nil? }
45
+
46
+ # Set the Authorization header if auth_token is provided
47
+ headers_with_auth = extra_headers.dup
48
+ headers_with_auth['Authorization'] = "Bearer #{auth_token}" if auth_token
49
+
50
+ headers_with_auth['Content-Type'] ||= 'application/json'
51
+
52
+ # Proceed with the request, passing the modified headers
53
+ request_with_retry(method, uri, body, headers_with_auth)
54
+ end
55
+ end
56
+
57
+ # Returns the options for retrying requests, including the number of retries and the sleep timer.
58
+ #
59
+ # @return [Hash] a hash containing retry options.
60
+ def retry_options
61
+ sleep_timer = lambda do |attempt|
62
+ wait = BASE_DELAY * (2**attempt - 1) # Exponential delay with each subsequent request attempt.
63
+ wait += rand(wait + 1..wait + MAX_REQUEST_RETRY_JITTER) # Add jitter to the delay window.
64
+ wait = [MAX_REQUEST_RETRY_DELAY, wait].min # Cap delay at MAX_REQUEST_RETRY_DELAY.
65
+ wait = [MIN_REQUEST_RETRY_DELAY, wait].max # Ensure delay is no less than MIN_REQUEST_RETRY_DELAY.
66
+ wait / 1000.to_f.round(2) # Convert ms to seconds
67
+ end
68
+
69
+ tries = 1 + [Integer(retry_count || DEFAULT_RETRIES), MAX_ALLOWED_RETRIES].min # Cap retries at MAX_ALLOWED_RETRIES
70
+
71
+ {
72
+ tries: tries,
73
+ sleep: sleep_timer,
74
+ on: SimpleAuthSdk::RateLimitEncountered
75
+ }
76
+ end
77
+
78
+ # Encodes the URI based on whether a base_uri is set.
79
+ #
80
+ # @param uri [String] the URI to encode.
81
+ # @return [String] the full encoded URI.
82
+ def encode_uri(uri)
83
+ path = base_uri ? Addressable::URI.new(path: uri).normalized_path : Addressable::URI.escape(uri)
84
+ url(path)
85
+ end
86
+
87
+ # Constructs the full URL by appending the path to the base URI.
88
+ #
89
+ # @param path [String] the path to append to the base URI.
90
+ # @return [String] the full URL.
91
+ def url(path)
92
+ "#{base_uri}#{path}"
93
+ end
94
+
95
+ # Merges additional headers into the existing headers hash.
96
+ #
97
+ # @param h [Hash] the headers to merge.
98
+ # @return [void]
99
+ # @raise [ArgumentError] if headers are not a hash.
100
+ def add_headers(h = {})
101
+ raise ArgumentError, 'Headers must be an object which responds to #to_hash' unless h.respond_to?(:to_hash)
102
+
103
+ @headers ||= {}
104
+ @headers.merge!(h.to_hash)
105
+ end
106
+
107
+ # Safely parses the JSON response body.
108
+ #
109
+ # @param body [String] the response body to parse.
110
+ # @return [Hash, String] the parsed JSON or raw body if parsing fails.
111
+ def safe_parse_json(body)
112
+ JSON.parse(body.to_s)
113
+ rescue JSON::ParserError
114
+ body
115
+ end
116
+
117
+ # Makes an HTTP request with retry logic.
118
+ #
119
+ # @param method [Symbol] the HTTP method to use (e.g., :get, :post).
120
+ # @param uri [String] the URI to make the request to.
121
+ # @param body [Hash] the request body.
122
+ # @param extra_headers [Hash] additional headers for the request.
123
+ # @return [Hash, String] the parsed response body, or raw response if JSON parsing fails.
124
+ def request_with_retry(method, uri, body = {}, extra_headers = {})
125
+ Retryable.retryable(retry_options) do
126
+ request(method, uri, body, extra_headers)
127
+ end
128
+ end
129
+
130
+ # Makes an HTTP request.
131
+ #
132
+ # @param method [Symbol] the HTTP method to use (e.g., :get, :post).
133
+ # @param uri [String] the URI to make the request to.
134
+ # @param body [Hash] the request body.
135
+ # @param extra_headers [Hash] additional headers for the request.
136
+ # @return [Hash, String] the parsed response body, or raw response if JSON parsing fails.
137
+ # @raise [SimpleAuthSdk::BadRequest] if the response code is 400.
138
+ # @raise [SimpleAuthSdk::Unauthorized] if the response code is 401.
139
+ # @raise [SimpleAuthSdk::AccessDenied] if the response code is 403.
140
+ # @raise [SimpleAuthSdk::NotFound] if the response code is 404.
141
+ # @raise [SimpleAuthSdk::RateLimitEncountered] if the response code is 429.
142
+ # @raise [SimpleAuthSdk::ServerError] if the response code is 500.
143
+ # @raise [SimpleAuthSdk::Unsupported] for other 4xx and 5xx response codes.
144
+ def request(method, uri, body = {}, extra_headers = {})
145
+ result = case method
146
+ when :get
147
+ @headers ||= {}
148
+ get_headers = @headers.merge({ params: body }).merge(extra_headers)
149
+ call(:get, encode_uri(uri), timeout, get_headers)
150
+ when :delete
151
+ @headers ||= {}
152
+ delete_headers = @headers.merge({ params: body })
153
+ call(:delete, encode_uri(uri), timeout, delete_headers)
154
+ when :delete_with_body
155
+ call(:delete, encode_uri(uri), timeout, headers, body.to_json)
156
+ else
157
+ get_headers = headers.merge(extra_headers)
158
+ call(method, encode_uri(uri), timeout, get_headers, body.to_json)
159
+ end
160
+ case result.code
161
+ when 200...226 then safe_parse_json(result.body)
162
+ when 400 then raise SimpleAuthSdk::BadRequest.new(result.body, code: result.code, headers: result.headers)
163
+ when 401 then raise SimpleAuthSdk::Unauthorized.new(result.body, code: result.code, headers: result.headers)
164
+ when 403 then raise SimpleAuthSdk::AccessDenied.new(result.body, code: result.code, headers: result.headers)
165
+ when 404 then raise SimpleAuthSdk::NotFound.new(result.body, code: result.code, headers: result.headers)
166
+ when 429 then raise SimpleAuthSdk::RateLimitEncountered.new(result.body, code: result.code, headers: result.headers)
167
+ when 500 then raise SimpleAuthSdk::ServerError.new(result.body, code: result.code, headers: result.headers)
168
+ else raise SimpleAuthSdk::Unsupported.new(result.body, code: result.code, headers: result.headers)
169
+ end
170
+ end
171
+
172
+ # Executes an HTTP request using rest-client.
173
+ #
174
+ # @param method [Symbol] the HTTP method to use (e.g., :get, :post).
175
+ # @param url [String] the full URL for the request.
176
+ # @param timeout [Integer] the timeout for the request in seconds.
177
+ # @param headers [Hash] the headers to include in the request.
178
+ # @param body [String, nil] the request body, if applicable.
179
+ # @return [RestClient::Response] the HTTP response.
180
+ # @raise [SimpleAuthSdk::RequestTimeout] if the request times out.
181
+ def call(method, url, timeout, headers, body = nil)
182
+ RestClient::Request.execute(
183
+ method: method,
184
+ url: url,
185
+ timeout: timeout,
186
+ headers: headers,
187
+ payload: body
188
+ )
189
+ rescue RestClient::Exception => e
190
+ case e
191
+ when RestClient::RequestTimeout
192
+ raise SimpleAuthSdk::RequestTimeout, e.message
193
+ else
194
+ e.response
195
+ end
196
+ end
197
+
198
+ # @!attribute [rw] base_uri
199
+ # @return [String] the base URI used for all requests.
200
+ def base_uri
201
+ SimpleAuthSdk.configuration.base_uri
202
+ end
203
+
204
+ def headers
205
+ @headers ||= {
206
+ 'Content-Type' => 'application/json'
207
+ }
208
+ end
209
+ end
210
+ end
211
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'base64'
4
+ require 'rest-client'
5
+ require 'uri'
6
+
7
+ require_relative 'mixins/httpproxy'
8
+
9
+ module SimpleAuthSdk
10
+ module Mixins
11
+ include SimpleAuthSdk::Mixins::HTTPProxy
12
+ end
13
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SimpleAuthSdk
4
+ VERSION = '0.1.0'
5
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'simple_auth_sdk/version'
4
+ require_relative './simple_auth_sdk/mixins'
5
+ require_relative './simple_auth_sdk/api/authentication_endpoints'
6
+ require_relative './simple_auth_sdk/configuration'
7
+
8
+ # The SimpleAuthSdk module provides a simple authentication SDK for Ruby applications.
9
+ module SimpleAuthSdk
10
+ class Error < StandardError; end
11
+
12
+ class << self
13
+ attr_accessor :configuration
14
+
15
+ # Configures the SimpleAuthSdk module.
16
+ #
17
+ # @yield [configuration] The configuration object to be modified.
18
+ # @yieldparam configuration [Configuration] The configuration object.
19
+ #
20
+ # @example Configuring the SDK:
21
+ # SimpleAuthSdk.configure do |config|
22
+ # config.api_key = 'YOUR_API_KEY'
23
+ # config.secret_key = 'YOUR_SECRET_KEY'
24
+ # end
25
+ #
26
+ def configure
27
+ self.configuration ||= Configuration.new
28
+ yield(configuration) if block_given?
29
+ configuration.validate!
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,4 @@
1
+ module SimpleAuthSdk
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,104 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: simple_auth_sdk
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Muhidin Hukic
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2024-08-09 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: addressable
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '2.7'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '2.7'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rest-client
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '2.1'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '2.1'
41
+ - !ruby/object:Gem::Dependency
42
+ name: retryable
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.0'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.0'
55
+ description: SimpleAuthSdk is a Ruby gem that provides simple authentication mechanisms
56
+ and tools for identity providers.
57
+ email:
58
+ - muhidinhukic1@gmail.com
59
+ executables: []
60
+ extensions: []
61
+ extra_rdoc_files: []
62
+ files:
63
+ - ".rspec"
64
+ - ".rubocop.yml"
65
+ - CHANGELOG.md
66
+ - CODE_OF_CONDUCT.md
67
+ - LICENSE.txt
68
+ - README.md
69
+ - Rakefile
70
+ - lib/simple_auth_sdk.rb
71
+ - lib/simple_auth_sdk/api/authentication_endpoints.rb
72
+ - lib/simple_auth_sdk/configuration.rb
73
+ - lib/simple_auth_sdk/exception.rb
74
+ - lib/simple_auth_sdk/mixins.rb
75
+ - lib/simple_auth_sdk/mixins/httpproxy.rb
76
+ - lib/simple_auth_sdk/version.rb
77
+ - sig/simple_auth_sdk.rbs
78
+ homepage: https://github.com/hukic-m/simple_auth_sdk
79
+ licenses:
80
+ - MIT
81
+ metadata:
82
+ homepage_uri: https://github.com/hukic-m/simple_auth_sdk
83
+ source_code_uri: https://github.com/hukic-m/simple_auth_sdk
84
+ changelog_uri: https://github.com/hukic-m/simple_auth_sdk/blob/main/CHANGELOG.md
85
+ post_install_message:
86
+ rdoc_options: []
87
+ require_paths:
88
+ - lib
89
+ required_ruby_version: !ruby/object:Gem::Requirement
90
+ requirements:
91
+ - - ">="
92
+ - !ruby/object:Gem::Version
93
+ version: 2.6.0
94
+ required_rubygems_version: !ruby/object:Gem::Requirement
95
+ requirements:
96
+ - - ">="
97
+ - !ruby/object:Gem::Version
98
+ version: '0'
99
+ requirements: []
100
+ rubygems_version: 3.4.10
101
+ signing_key:
102
+ specification_version: 4
103
+ summary: A Simple Authentication SDK for Roda deployable app simple_auth
104
+ test_files: []