duo_universal_rails 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 345f8175b91b67c43ceacc399dd2a0a7922be9e52300f8af4356acfe0241404a
4
+ data.tar.gz: 54ba6519678210538df2aed17c2b74e39632577dcbf5938cabbd90b908a636de
5
+ SHA512:
6
+ metadata.gz: 23ace59a3126c34eb90bcc78b2e823105ca444e47d1d6ab074f97585a0c8d11f71f199d77cbc032c061debc8a64e482aeb88075b2f71bfcc4cc361a2d6eb7739
7
+ data.tar.gz: 98817afd7fc3465db00e2afb889fb51ef0633b3e06a9cc5976e32de92d0d3d40d45b4df1061236bef1dd40d3af6052c1c07456d380870011292fcb92d276752e
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/CHANGELOG.md ADDED
@@ -0,0 +1 @@
1
+ # duo_universal_rails
@@ -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 suman5040@gmail.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/Gemfile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in duo_universal_rails.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
data/Gemfile.lock ADDED
@@ -0,0 +1,43 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ duo_universal_rails (0.1.0)
5
+ faraday (~> 0.11)
6
+ faraday_middleware (~> 0.14)
7
+ jwt (~> 1.5)
8
+
9
+ GEM
10
+ remote: https://rubygems.org/
11
+ specs:
12
+ diff-lcs (1.5.0)
13
+ faraday (0.17.5)
14
+ multipart-post (>= 1.2, < 3)
15
+ faraday_middleware (0.14.0)
16
+ faraday (>= 0.7.4, < 1.0)
17
+ jwt (1.5.6)
18
+ multipart-post (2.2.3)
19
+ rake (13.0.6)
20
+ rspec (3.11.0)
21
+ rspec-core (~> 3.11.0)
22
+ rspec-expectations (~> 3.11.0)
23
+ rspec-mocks (~> 3.11.0)
24
+ rspec-core (3.11.0)
25
+ rspec-support (~> 3.11.0)
26
+ rspec-expectations (3.11.1)
27
+ diff-lcs (>= 1.2.0, < 2.0)
28
+ rspec-support (~> 3.11.0)
29
+ rspec-mocks (3.11.1)
30
+ diff-lcs (>= 1.2.0, < 2.0)
31
+ rspec-support (~> 3.11.0)
32
+ rspec-support (3.11.1)
33
+
34
+ PLATFORMS
35
+ ruby
36
+
37
+ DEPENDENCIES
38
+ duo_universal_rails!
39
+ rake (~> 13.0)
40
+ rspec (~> 3.0)
41
+
42
+ BUNDLED WITH
43
+ 2.1.4
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Sahidur Rahman Suman
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,54 @@
1
+ # Duo Universal
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/duo_universal_rails`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Install the gem and add to the application's Gemfile by executing:
10
+
11
+ $ bundle add duo_universal_rails
12
+
13
+ If bundler is not being used to manage dependencies, install the gem by executing:
14
+
15
+ $ gem install duo_universal_rails
16
+
17
+ ## Usage
18
+
19
+ ```ruby
20
+ client = DuoUniversalRails::Client.new(client_id: ENV["DUO_CLIENT_ID"], client_secret: ENV["DUO_CLIENT_SECRET"], api_hostname: ENV["DUO_HOSTNAME"], redirect_uri: ENV["DUO_REDIRECT_URI"])
21
+
22
+ client.health_check.ping
23
+
24
+
25
+ client.auth.create_url(username: 'DUO_USER')
26
+
27
+ result = client.token.exchange_authorization_code_for_2fa_result(code: 'CODE', username: 'DUO_USER')
28
+
29
+ if result["sub"].present? && result["sub"] == 'username'
30
+ # Success
31
+ else
32
+ # Error
33
+ end
34
+
35
+
36
+ ```
37
+
38
+ ## Development
39
+
40
+ 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.
41
+
42
+ 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).
43
+
44
+ ## Contributing
45
+
46
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/duo_universal_rails. 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]/duo_universal_rails/blob/master/CODE_OF_CONDUCT.md).
47
+
48
+ ## License
49
+
50
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
51
+
52
+ ## Code of Conduct
53
+
54
+ Everyone interacting in the DuoUniversalRails project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/duo_universal_rails/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
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
+ task default: :spec
@@ -0,0 +1,96 @@
1
+ require "faraday"
2
+ require "faraday_middleware"
3
+ require 'jwt'
4
+
5
+ module DuoUniversalRails
6
+ class Client
7
+
8
+ attr_reader :client_id, :client_secret, :api_hostname, :redirect_uri, :state, :time_now, :adapter
9
+
10
+ def initialize(client_id:, client_secret:, api_hostname:, redirect_uri:, time_now: Time.now, state: Client.generate_state, adapter: Faraday.default_adapter)
11
+ @client_id = client_id
12
+ @client_secret = client_secret
13
+ @api_hostname = api_hostname
14
+ @redirect_uri = redirect_uri
15
+ @time_now = time_now
16
+ @state = state
17
+ @adapter = adapter
18
+ end
19
+
20
+ class << self
21
+ def generate_state
22
+ # Generate JTI_LENGTH length random value
23
+ SecureRandom.alphanumeric(Constant::JTI_LENGTH)
24
+ end
25
+
26
+ end
27
+
28
+ def https_api_hostname
29
+ "https://#{api_hostname}"
30
+ end
31
+
32
+ def health_check_path
33
+ Constant::OAUTH_V1_HEALTH_CHECK_ENDPOINT
34
+ end
35
+
36
+ def health_check_url
37
+ [https_api_hostname, health_check_path].join("")
38
+ end
39
+
40
+ def auth_path
41
+ Constant::OAUTH_V1_AUTHORIZE_ENDPOINT
42
+ end
43
+
44
+ def auth_url
45
+ [https_api_hostname, auth_path].join("")
46
+ end
47
+
48
+ def token_path
49
+ Constant::OAUTH_V1_TOKEN_ENDPOINT
50
+ end
51
+
52
+ def token_url
53
+ [https_api_hostname, token_path].join("")
54
+ end
55
+
56
+ def time_now_in_sec
57
+ time_now.to_i
58
+ end
59
+
60
+ def expire_in_sec
61
+ time_now_in_sec + Constant::FIVE_MINUTES_IN_SECONDS
62
+ end
63
+
64
+ def health_check
65
+ HealthCheckRequest.new(self)
66
+ end
67
+
68
+ def auth
69
+ AuthRequest.new(self)
70
+ end
71
+
72
+ def token
73
+ TokenRequest.new(self)
74
+ end
75
+
76
+ # The secret must be a string. A JWT::DecodeError will be raised if it isn't provided.
77
+ def create_jwt_payload(payload:)
78
+ JWT.encode payload, client_secret, Constant::SIG_ALGORITHM
79
+ end
80
+
81
+ def decode_jwt_token(token: nil)
82
+ JWT.decode token, client_secret, true, { algorithm: Constant::SIG_ALGORITHM }
83
+ end
84
+
85
+ def connection
86
+ @connection ||= Faraday.new(https_api_hostname) do |f|
87
+ f.adapter adapter # adds the adapter to the connection, defaults to `Faraday.default_adapter`
88
+ end
89
+ end
90
+
91
+ def inspect
92
+ "#<DuoUniversalRails::Client>"
93
+ end
94
+
95
+ end
96
+ end
@@ -0,0 +1,39 @@
1
+ module DuoUniversalRails
2
+ class Constant
3
+ CLIENT_ID_LENGTH = 20
4
+ CLIENT_SECRET_LENGTH = 40
5
+ JTI_LENGTH = 36
6
+ MINIMUM_STATE_LENGTH = 22
7
+ MAXIMUM_STATE_LENGTH = 1024
8
+ STATE_LENGTH = 36
9
+ SUCCESS_STATUS_CODE = 200
10
+ FIVE_MINUTES_IN_SECONDS = 300
11
+ # One minute in seconds
12
+ LEEWAY = 60
13
+
14
+ SIG_ALGORITHM = 'HS512'
15
+
16
+ ERR_USERNAME = 'The username is invalid.'
17
+ ERR_NONCE = 'The nonce is invalid.'
18
+ ERR_CLIENT_ID = 'The Duo client id is invalid.'
19
+ ERR_CLIENT_SECRET = 'The Duo client secret is invalid.'
20
+ ERR_API_HOST = 'The Duo api host is invalid'
21
+ ERR_REDIRECT_URI = 'No redirect uri'
22
+ ERR_CODE = 'Missing authorization code'
23
+ ERR_UNKNOWN = 'An unknown error has occurred.'
24
+ ERR_GENERATE_LEN = 'Length needs to be at least 22'
25
+
26
+ # ERR_STATE_LEN = ('State must be at least {MIN} characters long and no longer than {MAX} characters').format(
27
+ # MIN=MINIMUM_STATE_LENGTH,
28
+ # MAX=MAXIMUM_STATE_LENGTH
29
+ # )
30
+
31
+ # API_HOST_URI_FORMAT = "https://{}"
32
+ OAUTH_V1_HEALTH_CHECK_ENDPOINT = "/oauth/v1/health_check"
33
+ OAUTH_V1_AUTHORIZE_ENDPOINT = "/oauth/v1/authorize"
34
+ OAUTH_V1_TOKEN_ENDPOINT = "/oauth/v1/token"
35
+ # DEFAULT_CA_CERT_PATH = os.path.join(os.path.dirname(__file__), 'ca_certs.pem')
36
+
37
+ CLIENT_ASSERT_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
38
+ end
39
+ end
@@ -0,0 +1,3 @@
1
+ module DuoUniversalRails
2
+ class Error < StandardError; end
3
+ end
@@ -0,0 +1,20 @@
1
+ require "ostruct"
2
+
3
+ module DuoUniversalRails
4
+ class Object
5
+
6
+ def initialize(attributes)
7
+ @attributes = OpenStruct.new(attributes)
8
+ end
9
+
10
+ def method_missing(method, *args, &block)
11
+ attribute = @attributes.send(method, *args, &block)
12
+ attribute.is_a?(Hash) ? Object.new(attribute) : attribute
13
+ end
14
+
15
+ def respond_to_missing?(method, include_private = false)
16
+ true
17
+ end
18
+
19
+ end
20
+ end
@@ -0,0 +1,47 @@
1
+ module DuoUniversalRails
2
+ class Request
3
+ attr_reader :client
4
+
5
+ def initialize(client)
6
+ @client = client
7
+ end
8
+
9
+ def get_request(url, params: {}, headers: {})
10
+ handle_response client.connection.get(url, params, default_headers.merge(headers))
11
+ end
12
+
13
+ def post_request(url, params: {})
14
+ response = client.connection.post(url) do |req|
15
+ req.params = params
16
+ end
17
+
18
+ handle_response response
19
+ end
20
+
21
+
22
+ def default_headers
23
+ # {Authorization: "Bearer #{client.api_key}"}
24
+ end
25
+
26
+ def handle_response(response)
27
+ message = response.body["error"]
28
+
29
+ case response.status
30
+ when 400
31
+ raise Error, message
32
+ when 401
33
+ raise Error, message
34
+ when 403
35
+ raise Error, message
36
+ when 404
37
+ raise Error, message
38
+ when 429
39
+ raise Error, message
40
+ when 500
41
+ raise Error, message
42
+ end
43
+
44
+ response
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,90 @@
1
+ module DuoUniversalRails
2
+ class AuthRequest < Request
3
+
4
+ def create_url(username:)
5
+ query_params = build_auth_url_query_params(username: username)
6
+ url_query = query_params.to_a.map { |x| "#{x[0]}=#{x[1]}" }.join("&")
7
+ [client.auth_url, "?", url_query].join("")
8
+ end
9
+
10
+ def build_auth_url_query_params(username:)
11
+ {
12
+ response_type: 'code',
13
+ client_id: client.client_id,
14
+ request: request_jwt(username: username),
15
+ redirect_uri: client.redirect_uri,
16
+ scope: 'openid'
17
+
18
+ }
19
+ end
20
+
21
+
22
+ # We expect the value code to be present for this field.
23
+ # KEY - response_type, TYPE - string, REQUIRED - Yes
24
+
25
+ # Must match the value defined above.
26
+ # Means if you added scope is openid for authoraze params as scope openid then scope should be openid
27
+ # KEY - scope, TYPE - String, REQUIRED - Yes
28
+
29
+ # The time at which the request you are sending should expire.
30
+ # Duo recommends an exp value of five minutes.
31
+ # The timestamp format should be in seconds from Unix epoch.
32
+ # KEY - exp, TYPE - String, REQUIRED - Yes
33
+
34
+ # The Client ID (or Integration key) from the application's page in the Duo Admin Panel.
35
+ # KEY - client_id, TYPE - String, REQUIRED - Yes
36
+
37
+ # The URI where the end-user will be redirected after a successful auth.
38
+ # Must be a well-formed with a valid HTTPS URL and port, using a hostname.
39
+ # Maximum length: 1024 characters.
40
+ # KEY - redirect_uri, TYPE - String, REQUIRED - Yes
41
+
42
+
43
+ # A random, cryptographically secure value that the client must maintain throughout the authentication.
44
+ # We require a length of at least 16 characters and at most 1024 characters.
45
+ # KEY - state, TYPE - String, REQUIRED - Yes
46
+
47
+ # Unique name for the user in Duo. If a user has aliases in Duo, those are valid to send in this field.
48
+ # Subject to username normalization as configured for the application in the Admin Panel.
49
+ # KEY - duo_uname, TYPE = String, REQUIRED = Yes
50
+
51
+ # If provided, this field must match the client_id sent in this payload.
52
+ # KEY - iss, TYPE - String, REQUIRED - No
53
+
54
+ # This field must match the “API hostname" from the application's
55
+ # page in the Duo Admin Panel: https://{api_hostname}.
56
+ # KEY - aud, TYPE - String, REQUIRED - No
57
+
58
+ # f provided, this must be a random value that is cryptographically secure such that it is unguessable by a third party.
59
+ # We require a length of at least 16 characters and at most 1024 characters.
60
+ # KEY - nonce, TYPE - String, REQUIRED - No
61
+
62
+ # If provided and the value is true,
63
+ # then the authorization code will be returned under the attribute name of duo_code.
64
+ # KEY - use_duo_code_attribute, TYPE - Boolean, REQUIRED - No
65
+
66
+ def request_params(username:)
67
+ {
68
+ response_type: 'code',
69
+ scope: 'openid',
70
+ exp: client.expire_in_sec,
71
+ client_id: client.client_id,
72
+ redirect_uri: client.redirect_uri,
73
+ state: client.state,
74
+ duo_uname: username,
75
+ iss: client.client_id,
76
+ aud: client.https_api_hostname,
77
+ use_duo_code_attribute: true
78
+ }
79
+ end
80
+
81
+ def request_jwt(username:)
82
+ get_payload = request_params(username: username)
83
+ client.create_jwt_payload(payload: get_payload)
84
+ end
85
+
86
+
87
+
88
+
89
+ end
90
+ end
@@ -0,0 +1,80 @@
1
+ module DuoUniversalRails
2
+ class HealthCheckRequest < Request
3
+
4
+
5
+ def ping
6
+ parse_response post_request([client.health_check_path].join(""), params: health_check_params)
7
+ end
8
+
9
+
10
+ def health_check_params
11
+ {
12
+ client_id: client.client_id,
13
+ client_assertion: jwt_client_assertion
14
+ }
15
+ end
16
+
17
+
18
+ # The Client ID (or Integration key) from the application's page in the Duo Admin Panel.
19
+ # key = iss, TYPE = string, REQUIRED = Yes
20
+
21
+ # This should match the above iss value.
22
+ # key = sub, TYPE = string, REQUIRED = Yes
23
+
24
+ # This field must match the expected base URL where the request was sent,
25
+ # using the “API hostname" from the application's page in the
26
+ # Duo Admin Panel: https://{api_hostname}/oauth/v1/health_check.
27
+ # key = aud, TYPE = string, REQUIRED = Yes
28
+
29
+ # The time at which the request you are sending should expire. Duo recommends an exp value of five minutes.
30
+ # The timestamp format should be in seconds from Unix epoch.
31
+ # key = exp, TYPE = string, REQUIRED = Yes
32
+
33
+ # This should be a sufficiently random value unique to each JWT.
34
+ # key = jti, TYPE = string, REQUIRED = Yes
35
+
36
+ # The time at which the JWT was created.
37
+ # key = iat, TYPE = Integer, REQUIRED = No
38
+
39
+ def build_payload_params
40
+ {
41
+ iss: client.client_id,
42
+ sub: client.client_id,
43
+ aud: client.health_check_url,
44
+ exp: client.expire_in_sec,
45
+ jti: client.state,
46
+ iat: client.time_now_in_sec
47
+ }
48
+ end
49
+
50
+ def jwt_client_assertion
51
+ client.create_jwt_payload(payload: build_payload_params)
52
+ end
53
+
54
+
55
+ def parse_response(request)
56
+ str_to_json = JSON.parse(request.body)
57
+ response = Object.new(str_to_json)
58
+
59
+ if response.stat == "OK"
60
+ {
61
+ status: true,
62
+ message: "Success"
63
+ }
64
+ elsif response.stat == "FAIL"
65
+ msg = "Status: Fail, code: #{response.code}, message: #{response.message}"
66
+ {
67
+ status: false,
68
+ message: msg
69
+ }
70
+ else
71
+ {
72
+ status: false,
73
+ message: "Someting went wrong!"
74
+ }
75
+ end
76
+ end
77
+
78
+
79
+ end
80
+ end
@@ -0,0 +1,87 @@
1
+ module DuoUniversalRails
2
+ class TokenRequest < Request
3
+
4
+
5
+ def exchange_authorization_code_for_2fa_result(code: client.state, username:)
6
+ request = post_request([client.token_path].join(""), params: request_params(code: code))
7
+ parse_request = JSON.parse(request.body)
8
+ verify_token(token: parse_request["id_token"])[0]
9
+ end
10
+
11
+
12
+ # This must be equal to the string authorization_code.
13
+ # KEY - grant_type, TYPE - String, REQUIRED - Yes
14
+
15
+ # This must be equal to the string code received in the previous response.
16
+ # KEY - code, TYPE - String, REQUIRED - Yes
17
+
18
+ # This must be equal to the redirect URI sent in the request to the Authorization Request endpoint /oauth/v1/authorize.
19
+ # KEY - redirect_uri, TYPE - String, REQUIRED - Yes
20
+
21
+ # This must be equal to the string value urn:ietf:params:oauth:client-assertion-type:jwt-bearer,
22
+ # KEY - client_assertion_type, TYPE - String, REQUIRED - Yes
23
+
24
+ # See below for the required payload fields. See - client_assertion_payload method
25
+ # KEY - client_assertion, TYPE - JWT, REQUIRED - Yes
26
+
27
+ # The Client ID (or Integration key) from the application's page in the Duo Admin Panel.
28
+ # KEY - client_id, TYPE - String, REQUIRED - No
29
+
30
+
31
+ def request_params(code:)
32
+ {
33
+ grant_type: 'authorization_code',
34
+ code: code,
35
+ redirect_uri: client.redirect_uri,
36
+ client_assertion_type: Constant::CLIENT_ASSERT_TYPE,
37
+ client_assertion: jwt_client_assertion,
38
+ client_id: client.client_id
39
+ }
40
+ end
41
+
42
+
43
+
44
+
45
+ # The Client ID (or Integration key) from the application's page in the Duo Admin Panel.
46
+ # KEY - iss, TYPE - string, REQUIRED - Yes
47
+
48
+ # This should match the above iss value.
49
+ # KEY - sub, TYPE - string, REQUIRED - Yes
50
+
51
+ # This field must match the expected base URL where the request was sent, using the “API hostname" from the application's page in the Duo Admin Panel: https://{api_hostname}/oauth/v1/token
52
+ # KEY - aud, TYPE - string, REQUIRED - Yes
53
+
54
+ # The time at which the request you are sending should expire.
55
+ # Duo recommends an exp value of five minutes.
56
+ # The timestamp format should be in seconds from Unix epoch.
57
+ # KEY - exp, TYPE - Integer, REQUIRED - Yes
58
+
59
+ # This should be a sufficiently random value unique to each JWT.
60
+ # KEY - jti, TYPE - String, REQUIRED - Yes
61
+
62
+
63
+ # The time at which the JWT was created.
64
+ # KEY - exp, TYPE - Integer, REQUIRED - No
65
+
66
+ def client_assertion_payload
67
+ {
68
+ iss: client.client_id,
69
+ sub: client.client_id,
70
+ aud: client.token_url,
71
+ exp: client.expire_in_sec,
72
+ jti: client.state,
73
+ iat: client.time_now_in_sec
74
+ }
75
+ end
76
+
77
+ def jwt_client_assertion
78
+ client.create_jwt_payload(payload: client_assertion_payload)
79
+ end
80
+
81
+
82
+ def verify_token(token:)
83
+ client.decode_jwt_token(token: token)
84
+ end
85
+
86
+ end
87
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DuoUniversalRails
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "duo_universal_rails/version"
4
+
5
+ module DuoUniversalRails
6
+ autoload :Error, "duo_universal_rails/error"
7
+ autoload :Constant, "duo_universal_rails/constant"
8
+ autoload :Object, "duo_universal_rails/object"
9
+
10
+ autoload :Request, "duo_universal_rails/request"
11
+
12
+ autoload :HealthCheckRequest, "duo_universal_rails/requests/health_check_request"
13
+ autoload :AuthRequest, "duo_universal_rails/requests/auth_request"
14
+ autoload :TokenRequest, "duo_universal_rails/requests/token_request"
15
+
16
+
17
+ autoload :Client, "duo_universal_rails/client"
18
+
19
+ end
@@ -0,0 +1,4 @@
1
+ module DuoUniversalRails
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,111 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: duo_universal_rails
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Sahidur Rahman Suman
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2022-10-05 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: faraday
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '0.11'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '0.11'
27
+ - !ruby/object:Gem::Dependency
28
+ name: faraday_middleware
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '0.14'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '0.14'
41
+ - !ruby/object:Gem::Dependency
42
+ name: jwt
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '1.5'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '1.5'
55
+ description: Duo Universal Rails gem allows a webb developer to quickly add Duo's
56
+ interactive, self-service, two-factor authentication to any Ruby on Rails web authentication
57
+ form.
58
+ email:
59
+ - suman5040@gmail.com
60
+ executables: []
61
+ extensions: []
62
+ extra_rdoc_files: []
63
+ files:
64
+ - ".rspec"
65
+ - CHANGELOG.md
66
+ - CODE_OF_CONDUCT.md
67
+ - Gemfile
68
+ - Gemfile.lock
69
+ - LICENSE.txt
70
+ - README.md
71
+ - Rakefile
72
+ - lib/duo_universal_rails.rb
73
+ - lib/duo_universal_rails/client.rb
74
+ - lib/duo_universal_rails/constant.rb
75
+ - lib/duo_universal_rails/error.rb
76
+ - lib/duo_universal_rails/object.rb
77
+ - lib/duo_universal_rails/request.rb
78
+ - lib/duo_universal_rails/requests/auth_request.rb
79
+ - lib/duo_universal_rails/requests/health_check_request.rb
80
+ - lib/duo_universal_rails/requests/token_request.rb
81
+ - lib/duo_universal_rails/version.rb
82
+ - sig/duo_universal_rails.rbs
83
+ homepage: https://github.com/sahidursuman/duo_universal_rails
84
+ licenses:
85
+ - MIT
86
+ metadata:
87
+ homepage_uri: https://github.com/sahidursuman/duo_universal_rails
88
+ source_code_uri: https://github.com/sahidursuman/duo_universal_rails
89
+ changelog_uri: https://github.com/sahidursuman/duo_universal_rails/CHANGELOG.md
90
+ post_install_message:
91
+ rdoc_options: []
92
+ require_paths:
93
+ - lib
94
+ required_ruby_version: !ruby/object:Gem::Requirement
95
+ requirements:
96
+ - - ">="
97
+ - !ruby/object:Gem::Version
98
+ version: 2.5.0
99
+ required_rubygems_version: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ requirements: []
105
+ rubygems_version: 3.1.2
106
+ signing_key:
107
+ specification_version: 4
108
+ summary: Duo Universal Rails gem allows a webb developer to quickly add Duo's interactive,
109
+ self-service, two-factor authentication to any Ruby on Rails web authentication
110
+ form.
111
+ test_files: []