tozny-auth 0.1.4

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: f88e975adf4c7b8ca5dfc1bdc17dbfdbd4491815
4
+ data.tar.gz: 695c46c5741214b12eef87f2187602ebb7c47c50
5
+ SHA512:
6
+ metadata.gz: 8a7544b849a0a10306e46bb9b58554b75aaacd627328df4b26285349664104d3a3e7f35053a91b3d73afacb5f54d4d5a0bf9dfc6625b9d6449755d4154cc92a9
7
+ data.tar.gz: d34e998e76655590c97d8e9267675bbcef6571ab9b7bb8f408764d627efa2339673c5e7167221bae88b4a0fd41441e6c9bb5066e6135a4f8d5f262924adf0fb3
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ /.idea
11
+ .rakeTasks
12
+ *.gem
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.1.5
5
+ before_install: gem install bundler -v 1.12.2
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in tozny-auth.gemspec
4
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2014 Tozny, LLC. a Galois company.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
@@ -0,0 +1,51 @@
1
+ # Tozny::Auth
2
+
3
+ ## Installation
4
+
5
+ Add this line to your application's Gemfile:
6
+
7
+ ```ruby
8
+ gem 'tozny-auth'
9
+ ```
10
+
11
+ And then execute:
12
+
13
+ $ bundle
14
+
15
+ Or install it yourself as:
16
+
17
+ $ gem install tozny-auth
18
+
19
+ ## Usage
20
+ In your template, include jQuery and the Tozny jQuery library:
21
+ ```html
22
+ <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
23
+ <script src="https://s3-us-west-2.amazonaws.com/tozny/production/interface/javascript/v2/jquery.tozny.js"></script>
24
+ <script type="text/javascript">
25
+ $(document).ready(function() {
26
+ $('#tozny-login').tozny("sid_52fa6d0a3a290");
27
+ });
28
+ </script>
29
+ ```
30
+
31
+ In your controller (assuming you have access to a rails-like `params` hash):
32
+ ```ruby
33
+ require 'tozny/auth'
34
+ realm_key_id = 'sid_123456789'
35
+ realm_secret = '6f75.....190a8dbc7'
36
+ tozny = Tozny::Realm.new(realm_key_id, realm_secret)
37
+
38
+ if params[:tozny_action] == 'tozny_login'
39
+ user = tozny.check_login_locally(params[:signed_data], params[:signature])
40
+ if user and user.is_a?Hash
41
+ # Do some cool stuff with the user, because this was a successful login.
42
+ else
43
+ # Be sad (or happy in some cases) because the user did not log in successfully.
44
+ end
45
+ end
46
+ ```
47
+
48
+ ## Contributing
49
+
50
+ Bug reports and pull requests are welcome on GitHub at https://github.com/tozny/sdk-ruby
51
+
@@ -0,0 +1,10 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << "test"
6
+ t.libs << "lib"
7
+ t.test_files = FileList['test/**/*_test.rb']
8
+ end
9
+
10
+ task :default => :test
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "tozny/auth"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,11 @@
1
+ require 'tozny/auth/version'
2
+ require 'tozny/realm'
3
+ require 'tozny/user'
4
+
5
+ module Tozny
6
+ module Auth
7
+ # Your code goes here...
8
+ User = Tozny::User
9
+ Realm = Tozny::Realm
10
+ end
11
+ end
@@ -0,0 +1,61 @@
1
+ require 'openssl'
2
+ require 'base64'
3
+ require 'json'
4
+ require 'securerandom'
5
+
6
+ module Tozny
7
+ # utility class for tozny-specific cryptography and encoding
8
+ class Core
9
+
10
+ # encodes a string according to the base64url specification, including removing padding
11
+ # @param [String] str the string to encode
12
+ # @return [String] the base64url-encoded string
13
+ def self.base64url_encode(str)
14
+ Base64::strict_encode64(
15
+ str #str to decode
16
+ ) #remove padding
17
+ .tr('+/', '-_') #replace + with - and / with _
18
+ .tr('=', '')
19
+ end
20
+
21
+ # decodes a padding-stripped base64url string
22
+ # @param [String] str the base64url-encoded string
23
+ # @return [String] the decoded plaintext string
24
+ def self.base64url_decode(str)
25
+ Base64::strict_decode64(str.tr('-_', '+/') #replace - with + and _ with /
26
+ .ljust(str.length+(str.length % 4), '=')) #add padding
27
+ end
28
+
29
+ # checks the HMAC/SHA256 signature of a string
30
+ # @param [String] signature the signature to check against
31
+ # @param [String] str the signed data to check the signature against
32
+ # @param [String] secret the secret to check the signature against
33
+ # @return [Boolean] whether the signature matched
34
+ def self.check_signature(signature, str, secret)
35
+ expected_sig = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), secret, str)
36
+ expected_sig == signature
37
+ end
38
+
39
+ # base64url encodes and signs some data
40
+ # * yields a base64url-encoded data object AND base64url-encoded signature
41
+ # * the signature signs the base64-encoded data, NOT the raw data
42
+ # @param [String] data the raw data to be encoded
43
+ # @param [String] secret the secret to sign the encoded data with
44
+ # @return [Hash] a hash including the signed_data and a signature
45
+ def self.encode_and_sign(data, secret)
46
+ encoded_data = base64url_encode(data)
47
+ sig=OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha256'), secret, encoded_data)
48
+ encoded_sig = base64url_encode(sig)
49
+ return { #behold, the rare return statement
50
+ :signed_data => encoded_data,
51
+ :signature => encoded_sig
52
+ }
53
+ end
54
+
55
+ # generates a nonce (number used once)
56
+ # @return [String] a hexadecimal nonce
57
+ def self.generate_nonce
58
+ OpenSSL::Digest::SHA256.hexdigest SecureRandom.random_bytes(8)
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,5 @@
1
+ module Tozny
2
+ module Auth
3
+ VERSION = '0.1.4'
4
+ end
5
+ end
@@ -0,0 +1,215 @@
1
+ require 'tozny/user'
2
+ require 'json'
3
+ require 'net/http'
4
+ require 'uri'
5
+
6
+ module Tozny
7
+ class Realm
8
+ attr_accessor :realm_key_id, :realm_secret, :api_url, :user_api
9
+
10
+ def initialize(realm_key_id, realm_secret, api_url = nil)
11
+ #self.realm_key_id = realm_key_id
12
+ #self.realm_secret = realm_secret
13
+
14
+ #set the API URL
15
+ if !api_url.nil?
16
+ self.api_url = api_url
17
+ elsif !(ENV['API_URL'].nil?)
18
+ self.api_url=ENV['API_URL']
19
+ else
20
+ self.api_url='https://api.tozny.com/index.php'
21
+ end
22
+ unless self.api_url.is_a? URI #don't try to parse a URI instance into a URI, as this will break
23
+ self.api_url = URI.parse(self.api_url)
24
+ end
25
+
26
+ self.set_new_realm(realm_key_id, realm_secret)
27
+
28
+ end
29
+
30
+ # use a new realm_key_id and realm_secret. updates the user_api handle to reflect this change as well.
31
+ # @param [String] realm_key_id
32
+ # @param [String] realm_secret
33
+ # @return [TrueClass] will always return true
34
+ def set_new_realm (realm_key_id, realm_secret)
35
+ self.realm_key_id = realm_key_id
36
+ self.realm_secret = realm_secret
37
+ if self.user_api.is_a? ::Tozny::User
38
+ self.user_api.set_new_realm(realm_key_id)
39
+ else
40
+ self.user_api = ::Tozny::User.new(realm_key_id, api_url)
41
+ end
42
+ true
43
+ end
44
+
45
+ # verify a login and extract user information from a signed packet forwarded to the server
46
+ # @param [String] signed_data the base64URL data to validate
47
+ # @param [String] signature the string representation of the signature to check the login with
48
+ # @return [Hash, FalseClass] the login information or false if the login did not check out
49
+ def check_login_locally(signed_data, signature)
50
+ if check_signature(signed_data, signature)
51
+ login_info = JSON.parse(::Tozny::Core.base64url_decode(signed_data))
52
+ return false if login_info[:expires_at] < Time.now.to_i
53
+ login_info
54
+ else
55
+ false
56
+ end
57
+ end
58
+
59
+ # verify a login from a user and session id. Does not return complete login information.
60
+ # @param [String] user_id the user_id of the login to check
61
+ # @param [String] session_id the session_id of the login to check
62
+ # @return [Hash] the return from the API
63
+ def check_login_via_api(user_id, session_id) #NOTE: this only returns true/false. You need to parse the data locally. See Tozny::Core.base64url_decode
64
+ raw_call({
65
+ :method => 'realm.check_valid_login',
66
+ :user_id => user_id,
67
+ :session_id => session_id
68
+ })[:return] == 'true'
69
+ end
70
+
71
+ # Add a user to a closed realm
72
+ # @param [String] defer 'true' or 'false', defines whether the user should be deferred to later be completed by the app
73
+ # @param [Hash] meta any metadata to be added to the user (eg, favorite color or mother's home address). All meta will be stored as strings
74
+ # @param [String, OpenSSL::PKey::RSA] pub_key the public key of the user to be added. Only necessary
75
+ # @return [Hash, FalseClass] the user in its current (incomplete if defer is 'true' state)
76
+ # @raise ArgumentError if there is no pubkey when there should be one
77
+ def user_add(defer = 'false', meta, pub_key)
78
+ unless pub_key.nil?
79
+ if pub_key.is_a? String
80
+ pub_key = OpenSSL::PKey::RSA.new pub_key
81
+ end
82
+ pub_key = pub_key.public_key if pub_key.private?
83
+ end
84
+
85
+ request_obj = {
86
+ :method => 'realm.user_add',
87
+ :defer => defer
88
+ }
89
+ if defer == 'false'
90
+ raise ArgumentError, 'Must provide a public key if not using deferred enrollment' if pub_key.nil?
91
+ request_obj[:pub_key] = pub_key
92
+ end
93
+
94
+ unless meta.nil?
95
+ request_obj[:extra_fields] = Tozny::Core.base64url_encode(meta.to_json)
96
+ end
97
+
98
+ user = raw_call request_obj
99
+ return false unless user[:return] == 'ok'
100
+ user
101
+ end
102
+
103
+ # update a user's meta fields
104
+ # * Note: all meta fields are stored as strings
105
+ # @param [String] user_id
106
+ # @param [Hash{Symbol,String=>Object}] meta the metadata fields to update, along with their new values
107
+ # @return [Hash] the updated user
108
+ def user_update(user_id, meta)
109
+ raw_call({
110
+ :method => 'realm.user_update',
111
+ :user_id => user_id,
112
+ :extra_fields => Tozny::Core::base64url_encode(meta.to_json)
113
+ })
114
+ end
115
+
116
+ # @param [String] user_id
117
+ # @return [Hash] the result of the request to the API
118
+ def user_delete(user_id)
119
+ raw_call({
120
+ :method => 'realm.user_delete',
121
+ :user_id => user_id
122
+ })
123
+ end
124
+
125
+ # retrieve a user's information
126
+ # * Note: all meta fields are stored as strings
127
+ # @param [String] user_id the id or email (if is_id = false) of the user to get
128
+ # @param [Boolean] is_id true if looking up the user by id, false if looking up by email. defaults to true
129
+ # @return [Hash] the user's information
130
+ # @raise ArgumentError on failed lookup
131
+ def user_get(user_id, is_id = true)
132
+ request_obj = {
133
+ :method => 'realm.user_get'
134
+ }
135
+ if is_id
136
+ request_obj[:user_id] = user_id
137
+ else
138
+ request_obj[:tozny_email] = user_id
139
+ end
140
+
141
+ user = raw_call(request_obj)
142
+ if user.nil? or user[:results].nil?
143
+ raise ArgumentError, ('No user was found for '+(is_id ? 'id' : 'email')+': '+user_id+'.')
144
+ end
145
+ user[:results]
146
+ end
147
+
148
+ # performs a device add call
149
+ # @param [String] user_id
150
+ # @return [Hash] the result of the call: keys include :user_id, :temp_key, :secret_enrollment_url, and :key_id
151
+ def user_device_add(user_id)
152
+ raw_call({
153
+ :method=>'realm.user_device_add',
154
+ :user_id=>user_id
155
+ })
156
+ end
157
+
158
+ # create an OOB challenge question session
159
+ # @param [Hash<Symbol, String>, String] question either a question hash, as specified by the options, or the text of a question to be presented to the user. Required.
160
+ # @option question [String] :question The text of the question to be presented to the user
161
+ # @option question [String] :success The URL the user's browser should be redirected to after successful authentication
162
+ # @option question [String] :error The URL the user's browser should be redirected to after unsuccessful authentication
163
+ # @param [String] success_url The URL the user's browser should be redirected to after successful authentication if not specified in the question object
164
+ # @param [String] error_url The URL the user's browser should be redirected to after unsuccessful authentication if not specified in the question object
165
+ # @param [String] user_id optional. The user who should answer the question.
166
+ # TODO: support URI objects instead of strings for success and error
167
+ # @return [Hash] the result of the API call
168
+ def question_challenge(question, success_url, error_url, user_id)
169
+ raise ArgumentError, 'question must either be a string or an options hash as specified' unless question.is_a?String or question.is_a?Hash
170
+ final_question = nil #scope final_question and prevent linting errors
171
+ if question.is_a?Hash
172
+ final_question = question
173
+ final_question[:type] = 'callback'
174
+ else
175
+ if success_url.is_a?String or error_url.is_a?String
176
+ final_question = {
177
+ :type => 'callback',
178
+ :question => question
179
+ }
180
+ final_question[:success] = success_url if success_url.is_a?String
181
+ final_question[:error] = error_url if error_url.is_a?String
182
+ else
183
+ final_question = {
184
+ :type => 'question',
185
+ :question => question
186
+ }
187
+ end
188
+ end
189
+ request_obj = {
190
+ :method => 'realm.question_challenge',
191
+ :question => final_question
192
+ }
193
+ request_obj[:user_id] = user_id if user_id.is_a?String
194
+ raw_call request_obj
195
+ end
196
+
197
+ # perform a raw(ish) API call
198
+ # @param [Hash{Symbol, String => Object}] request_obj The request to conduct. Should include a :method at the least. Prefer symbol keys to string keys
199
+ # @return [Object] The parsed result of the request. NOTE: most types will be stringified for most requests
200
+ def raw_call(request_obj)
201
+ request_obj[:nonce] = Tozny::Core.generate_nonce #generate the nonce
202
+ request_obj[:expires_at] = Time.now.to_i + 5*60 # UNIX timestamp for now +5 min TODO: does this work with check_login_via_api, or should it default to a passed in expires_at?
203
+ unless request_obj.key?('realm_key_id') || request_obj.key?(:realm_key_id) #check for both string and symbol
204
+ #TODO: how should we handle conflicts of symbol and string keys?
205
+ request_obj[:realm_key_id] = realm_key_id
206
+ end
207
+ encoded_params = Tozny::Core.encode_and_sign(request_obj.to_json, realm_secret) #make a proper request of it.
208
+ request_url = api_url #copy the URL to a local variable so that we can add the query params
209
+ request_url.query = URI.encode_www_form encoded_params #encode signed_data and signature as query params
210
+ #p request_url
211
+ http_result = Net::HTTP.get(request_url)
212
+ JSON.parse(http_result, {:symbolize_names => true}) #TODO: handle errors
213
+ end
214
+ end
215
+ end
@@ -0,0 +1,52 @@
1
+ require 'tozny/auth/common'
2
+
3
+ module Tozny
4
+ class User
5
+ attr_accessor :realm_key_id, :api_url
6
+ def initialize(realm_key_id, api_url = nil)
7
+
8
+ if !api_url.nil?
9
+ self.api_url = api_url
10
+ elsif !(ENV['API_URL'].nil?)
11
+ self.api_url=ENV['API_URL']
12
+ else
13
+ self.api_url='https://api.tozny.com/index.php'
14
+ end
15
+
16
+ unless self.api_url.is_a? URI
17
+ self.api_url = URI.parse(self.api_url)
18
+ end
19
+
20
+ self.set_new_realm(realm_key_id)
21
+ end
22
+
23
+ def check_session_status(session_id)
24
+ raw_call({
25
+ :method => 'user.check_session_status',
26
+ :session_id => session_id
27
+ }).has_key?(:signed_data)
28
+ end
29
+
30
+ # use a new realm_key_id
31
+ # @param [String] realm_key_id
32
+ # @return [TrueClass] will always return true
33
+ def set_new_realm (realm_key_id)
34
+ self.realm_key_id = realm_key_id
35
+ true
36
+ end
37
+
38
+ # perform a raw(ish) API call
39
+ # @param [Hash{Symbol, String => Object}] request_obj The request to conduct. Should include a :method at the least. Prefer symbol keys to string keys
40
+ # @return [Object] The parsed result of the request. NOTE: most types will be stringified for most requests
41
+ def raw_call(request_obj)
42
+ unless request_obj.key?('realm_key_id') || request_obj.key?(:realm_key_id) #check for both string and symbol
43
+ #TODO: how should we handle conflicts of symbol and string keys?
44
+ request_obj[:realm_key_id] = realm_key_id
45
+ end
46
+ request_url = api_url #copy the URL to a local variable so that we can add the query params
47
+ request_url.query = URI.encode_www_form request_obj #encode request as query params
48
+ #p request_url
49
+ JSON.parse(Net::HTTP.get(request_url), {:symbolize_names => true})
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,36 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'tozny/auth/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = 'tozny-auth'
8
+ spec.version = Tozny::Auth::VERSION
9
+ spec.authors = ['Ethan Bell / emanb29']
10
+ spec.email = ['eb@ethanbell.me']
11
+ spec.license = 'Apache-2.0'
12
+
13
+ spec.summary = %q{Tozny Ruby SDK}
14
+ spec.description = %q{A set of methods to more conveniently access the Tozny authentication API as a RP of Tozny from Ruby}
15
+ spec.homepage = 'https://github.com/tozny/sdk-ruby'
16
+
17
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
18
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
19
+ # if spec.respond_to?(:metadata)
20
+ # spec.metadata['allowed_push_host'] = 'TODO: What should this be???'
21
+ # else
22
+ # raise 'RubyGems 2.0 or newer is required to protect against public gem pushes.'
23
+ # end
24
+
25
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
26
+ spec.bindir = 'exe'
27
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
28
+ spec.require_paths = ['lib']
29
+
30
+ spec.add_development_dependency 'bundler', '~> 1.12'
31
+ spec.add_development_dependency 'rake', '~> 10.0'
32
+ spec.add_development_dependency 'minitest', '~> 5.0'
33
+
34
+ # Only with ruby 2.0.x
35
+ spec.required_ruby_version = '~> 2.0'
36
+ end
@@ -0,0 +1,27 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <module type="RUBY_MODULE" version="4">
3
+ <component name="CompassSettings">
4
+ <option name="compassExecutableFilePath" value="C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/compass-1.0.3/bin/compass" />
5
+ </component>
6
+ <component name="FacetManager">
7
+ <facet type="gem" name="Ruby Gem">
8
+ <configuration>
9
+ <option name="GEM_APP_ROOT_PATH" value="$MODULE_DIR$" />
10
+ <option name="GEM_APP_TEST_PATH" value="$MODULE_DIR$/test" />
11
+ <option name="GEM_APP_LIB_PATH" value="$MODULE_DIR$/lib" />
12
+ </configuration>
13
+ </facet>
14
+ </component>
15
+ <component name="NewModuleRootManager" inherit-compiler-output="true">
16
+ <exclude-output />
17
+ <content url="file://$MODULE_DIR$">
18
+ <sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
19
+ <excludeFolder url="file://$MODULE_DIR$/.bundle" />
20
+ <excludeFolder url="file://$MODULE_DIR$/vendor/bundle" />
21
+ </content>
22
+ <orderEntry type="jdk" jdkName="ruby-2.1.5-p273" jdkType="RUBY_SDK" />
23
+ <orderEntry type="sourceFolder" forTests="false" />
24
+ <orderEntry type="library" scope="PROVIDED" name="bundler (v1.12.2, ruby-2.1.5-p273) [gem]" level="application" />
25
+ <orderEntry type="library" scope="PROVIDED" name="minitest (v5.8.4, ruby-2.1.5-p273) [gem]" level="application" />
26
+ </component>
27
+ </module>
metadata ADDED
@@ -0,0 +1,102 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: tozny-auth
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.4
5
+ platform: ruby
6
+ authors:
7
+ - Ethan Bell / emanb29
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2016-06-27 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.12'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.12'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: minitest
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '5.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '5.0'
55
+ description: A set of methods to more conveniently access the Tozny authentication
56
+ API as a RP of Tozny from Ruby
57
+ email:
58
+ - eb@ethanbell.me
59
+ executables: []
60
+ extensions: []
61
+ extra_rdoc_files: []
62
+ files:
63
+ - ".gitignore"
64
+ - ".travis.yml"
65
+ - Gemfile
66
+ - LICENSE
67
+ - README.md
68
+ - Rakefile
69
+ - bin/console
70
+ - bin/setup
71
+ - lib/tozny/auth.rb
72
+ - lib/tozny/auth/common.rb
73
+ - lib/tozny/auth/version.rb
74
+ - lib/tozny/realm.rb
75
+ - lib/tozny/user.rb
76
+ - tozny-auth.gemspec
77
+ - tozny-auth.iml
78
+ homepage: https://github.com/tozny/sdk-ruby
79
+ licenses:
80
+ - Apache-2.0
81
+ metadata: {}
82
+ post_install_message:
83
+ rdoc_options: []
84
+ require_paths:
85
+ - lib
86
+ required_ruby_version: !ruby/object:Gem::Requirement
87
+ requirements:
88
+ - - "~>"
89
+ - !ruby/object:Gem::Version
90
+ version: '2.0'
91
+ required_rubygems_version: !ruby/object:Gem::Requirement
92
+ requirements:
93
+ - - ">="
94
+ - !ruby/object:Gem::Version
95
+ version: '0'
96
+ requirements: []
97
+ rubyforge_project:
98
+ rubygems_version: 2.4.5.1
99
+ signing_key:
100
+ specification_version: 4
101
+ summary: Tozny Ruby SDK
102
+ test_files: []