handle-system-rest 0.1.1

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: 80560da22c69f15df93fe8e75c12627751d4a67d2737d872677d7e6acca7eb3c
4
+ data.tar.gz: fc09852264bb245a026acfa8efe66fed8c6e85d71140064e120bda81a54326b8
5
+ SHA512:
6
+ metadata.gz: 518f266900d680dcc2b826042187109fc7addd8f73a5395500e854be76619ec04d6e0c987737b322b0f4dd083ecc029cc7ce438141f0ae011d1d39cf1842884f
7
+ data.tar.gz: f29c169459e00f9374b8172f82337b9d1f5a6b220a4238ae1d384be2d72b1bf3c6e1d7097502adab74989ce82c84a9e15cc83bf88fa4c443521aa192a909b0ed
data/.gitignore ADDED
@@ -0,0 +1,14 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ .DS_Store
10
+ Gemfile.lock
11
+ *.gem
12
+
13
+ # rspec failure tracking
14
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.travis.yml ADDED
@@ -0,0 +1,6 @@
1
+ ---
2
+ language: ruby
3
+ cache: bundler
4
+ rvm:
5
+ - 2.6.5
6
+ before_install: gem install bundler -v 2.1.4
data/Gemfile ADDED
@@ -0,0 +1,7 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in handle_system.gemspec
4
+ gemspec
5
+
6
+ gem "rake", "~> 12.0"
7
+ gem "rspec", "~> 3.0"
data/LICENSE.txt ADDED
@@ -0,0 +1,205 @@
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 2012 Penn State University
190
+ Copyright 2013 University of Notre Dame, Northwestern University, and Data Curation Experts
191
+ Copyright 2014 Data Curation Experts
192
+ Additional copyright may be held by others, as reflected in the commit log
193
+
194
+
195
+ Licensed under the Apache License, Version 2.0 (the "License");
196
+ you may not use this file except in compliance with the License.
197
+ You may obtain a copy of the License at
198
+
199
+ http://www.apache.org/licenses/LICENSE-2.0
200
+
201
+ Unless required by applicable law or agreed to in writing, software
202
+ distributed under the License is distributed on an "AS IS" BASIS,
203
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
204
+ See the License for the specific language governing permissions and
205
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,102 @@
1
+ # HandleSystem
2
+
3
+ A Ruby library for interfacing with the [Handle System](http://handle.net/) JSON REST API.
4
+
5
+ ## Handle server requirements
6
+
7
+ This library works with Handle System version 8 or higher. For older versions of the Handle System, which didn't have a JSON API, consider using mbklien's [Handle](https://github.com/mbklein/handle) library.
8
+
9
+ ### Private key conversion
10
+
11
+ Before you start using the library, you need to convert your Handle server's private key into PEM format. The Handle Server distribution directory (e.g., `/hs/handle-9.2.0`) has a utility, `hdl-convert-key`, for doing this. Your private key (`admpriv.bin`) is in the server directory (e.g., `/hs/svr_1`).
12
+
13
+ On the Handle server, Run this command to convert the file:
14
+
15
+ ```
16
+ /hs/handle-9.2.0/bin/hdl-convert-key /hs/svr_1/admpriv.bin -o /hs/svr_1/admpriv.pem
17
+ ```
18
+
19
+ Download that `admpriv.pem` file for use with this library.
20
+
21
+ ## Installation
22
+
23
+ Add this line to your application's Gemfile:
24
+
25
+ gem 'handle-system-rest'
26
+
27
+ And then execute:
28
+
29
+ $ bundle
30
+
31
+ Or install it yourself as:
32
+
33
+ $ gem install handle-system-rest
34
+
35
+ ## Usage
36
+
37
+ ```ruby
38
+ require 'handle_system'
39
+
40
+ server = '216.58.217.206:8000' # server in the form of ip-address:port
41
+ hs_admin = '300:0.NA/20.123.4567' # the handle server admin
42
+ private_key = '/path/to/admpriv.pem' # path to private key we downloaded above
43
+
44
+ # connect to the handle server
45
+ handle_client = HandleSystem::Client.new(server, hs_admin, private_key)
46
+
47
+ # the url we want to register with the handle system
48
+ hyrax_url = 'https://hyrax.example.edu/concern/theses/6h440t294'
49
+
50
+ # we need to create a unique handle identifier in the form of 'prefix/suffix'
51
+
52
+ prefix = '20.123.45678' # your handle.net registered prefix
53
+ suffix = '2' # this can be any unique identifier
54
+ handle = prefix + '/' + suffix
55
+
56
+ # register our url and get back a new persistent url
57
+ handle_url = handle_client.create(handle, hyrax_url)
58
+
59
+ puts handle_url #=> "http://hdl.handle.net/20.123.45678/2"
60
+
61
+ # get back our original url if we supply the handle
62
+ hyrax_url = handle_client.get(handle).url
63
+
64
+ puts hyrax_url #=> "https://hyrax.example.edu/concern/theses/6h440t294"
65
+
66
+ # we can also delete our handle entry
67
+ result = handle_client.delete(handle)
68
+
69
+ puts result.to_s #=> true
70
+
71
+ # client will throw an AuthenticationError if something went wrong while
72
+ # authenticating with the handle server
73
+
74
+ begin
75
+ HandleSystem::Client.new(server, 'bad-admin', private_key)
76
+ rescue HandleSystem::AuthenticationError => e
77
+ puts 'AuthenticationError'
78
+ puts ' message: ' + e.message
79
+ end
80
+
81
+ # client will throw an Error if something went wrong while creating, updating,
82
+ # or deleting a handle
83
+
84
+ begin
85
+ handle_client.create('bad-handle', hyrax_url)
86
+ rescue HandleSystem::Error => e
87
+ puts 'Error for bad handle id'
88
+ puts ' code: ' + e.response_code.to_s
89
+ puts ' handle: ' + e.handle
90
+ puts ' message: ' + e.message
91
+ end
92
+
93
+ begin
94
+ handle_client.delete('bad-handle')
95
+ rescue HandleSystem::Error => e
96
+ puts 'Error when trying to delete a non-existant handle'
97
+ puts ' code: ' + e.response_code.to_s
98
+ puts ' handle: ' + e.handle
99
+ puts ' message: ' + e.message
100
+ end
101
+
102
+ ```
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "handle_system"
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(__FILE__)
data/bin/setup ADDED
@@ -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,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/handle_system/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'handle-system-rest'
7
+ spec.version = HandleSystem::VERSION
8
+ spec.authors = ['David Walker']
9
+ spec.email = ['dwalker@calstate.edu']
10
+
11
+ spec.summary = 'A library for interfacing with the Handle System JSON REST API.'
12
+ spec.description = spec.summary + ' This gem works with Handle System ' +
13
+ 'version 8 or higher. For older versions of the ' +
14
+ "Handle System, which didn't have a JSON API, " +
15
+ 'consider using the handle-system gem'
16
+ spec.homepage = 'https://github.com/csuscholarworks/handle-system'
17
+ spec.license = 'APACHE'
18
+ spec.required_ruby_version = Gem::Requirement.new('>= 2.5.0')
19
+
20
+ spec.metadata['homepage_uri'] = spec.homepage
21
+ spec.metadata['source_code_uri'] = spec.homepage
22
+ spec.metadata['changelog_uri'] = 'https://github.com/csuscholarworks/handle-system/README.md'
23
+
24
+ # Specify which files should be added to the gem when it is released.
25
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
26
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
27
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
28
+ end
29
+ spec.bindir = 'exe'
30
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
31
+ spec.require_paths = ['lib']
32
+
33
+ spec.add_dependency 'httparty', '~> 0.18'
34
+ spec.add_development_dependency 'solargraph'
35
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ module HandleSystem
4
+ #
5
+ # Handle System client
6
+ #
7
+ # @author David Walker
8
+ #
9
+ class Client
10
+ #
11
+ # New Handle System client
12
+ #
13
+ # @param [String] server ip_address:port, e.g., 123.456.78.9:8000
14
+ # @param [String] hs_admin handle administrator
15
+ # @param [String] priv_key_path file path to private key
16
+ #
17
+ def initialize(server, hs_admin, priv_key_path)
18
+ @http_client = HttpClient.new(server, hs_admin, priv_key_path)
19
+ @handle_base = 'http://hdl.handle.net/'
20
+ end
21
+
22
+ #
23
+ # Create a new handle
24
+ #
25
+ # @param [String] handle e.g., 20.500.12345/876
26
+ # @param [String] url the url we want to register
27
+ # @param [String] email [optional] email address to add to record
28
+ # @param [String] hs_admin [optional] handle administrator to add to record
29
+ #
30
+ # @return [string] the new handle url at hdl.handle.net
31
+ #
32
+ def create(handle, url, email = nil, hs_admin = nil)
33
+ body = Record.new.from_values(handle, url, email, hs_admin).json
34
+ json = @http_client.put_it('/handles/' + handle, body)
35
+ @handle_base + json['handle']
36
+ end
37
+
38
+ # creating and updating handle records is the same thing
39
+ alias update create
40
+
41
+ #
42
+ # Return the full record for a handle
43
+ #
44
+ # @param [String] handle handle identifier
45
+ #
46
+ # @return [<JSON>] the handle record
47
+ #
48
+ def get(handle)
49
+ json = @http_client.get_it('/handles/' + handle)
50
+ Record.new.from_json(json)
51
+ end
52
+
53
+ #
54
+ # Delete a handle
55
+ #
56
+ # @param [String] handle handle identifier
57
+ #
58
+ # @return [Boolean] true if we deleted the record
59
+ #
60
+ def delete(handle)
61
+ json = @http_client.delete_it('/handles/' + handle)
62
+ return true if json['responseCode'] == 1
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module HandleSystem
4
+ #
5
+ # A basic Exception class to wrap the handle server errors
6
+ #
7
+ # @author David Walker
8
+ #
9
+ class Error < StandardError
10
+ # @return [Intenger] handle protocol response code for the message
11
+ attr_reader :response_code
12
+
13
+ # @return [String] the handle specified in the request
14
+ attr_reader :handle
15
+
16
+ #
17
+ # New Handle server Error
18
+ #
19
+ # @param [Integer] code handle protocol response code for the message
20
+ # @param [String] handle the handle specified in the request
21
+ # @param [String] message error message
22
+ #
23
+ def initialize(code, handle, message)
24
+ @response_code = code.to_int unless code.nil?
25
+ @handle = handle
26
+ super(message)
27
+ end
28
+ end
29
+
30
+ #
31
+ # Handle server authentication error
32
+ #
33
+ # @author David Walker
34
+ #
35
+ class AuthenticationError < StandardError; end
36
+ end
@@ -0,0 +1,168 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'base64'
4
+ require 'httparty'
5
+ require 'securerandom'
6
+
7
+ module HandleSystem
8
+ #
9
+ # HTTP utility class for Handle client
10
+ #
11
+ # Provides some convenience methods so we don't have to set headers and
12
+ # options with each request, checks for and throws errors reported by
13
+ # the handle server, and does the work of acquiring a session
14
+ #
15
+ # @author David Walker
16
+ #
17
+ class HttpClient
18
+ include HTTParty
19
+
20
+ #
21
+ # New Handle HTTP client
22
+ #
23
+ # @param [String] server ip_address:port, e.g., 123.456.78.9:8000
24
+ # @param [String] hs_admin handle administrator
25
+ # @param [String] priv_key_path file path to private key
26
+ #
27
+ def initialize(server, hs_admin, priv_key_path)
28
+ @hs_admin = hs_admin
29
+ @private_key_path = priv_key_path
30
+ @base_url = 'https://' + server + '/api'
31
+ @session_id = initialize_session
32
+ end
33
+
34
+ #
35
+ # Send a get request
36
+ #
37
+ # @param [String] path relative path from /api end-point
38
+ #
39
+ # @raise HandleSystem::Error if we got an error from the server
40
+ # @return [JSON] parsed json response from handle server
41
+ #
42
+ def get_it(path)
43
+ url = @base_url + path
44
+ json = self.class.get(url, options).parsed_response
45
+ check_errors(json)
46
+ json
47
+ end
48
+
49
+ #
50
+ # Send a put request
51
+ #
52
+ # @param [String] path relative path from /api end-point
53
+ # @param [String] body json data object
54
+ #
55
+ # @raise HandleSystem::Error if we got an error from the server
56
+ # @return [JSON] parsed json response from handle server
57
+ #
58
+ def put_it(path, body)
59
+ url = @base_url + path
60
+ json = self.class.put(url, body: body, **options).parsed_response
61
+ check_errors(json)
62
+ json
63
+ end
64
+
65
+ #
66
+ # Send a delete request
67
+ #
68
+ # @param [String] path relative path from /api end-point
69
+ #
70
+ # @raise HandleSystem::Error if we got an error from the server
71
+ # @return [JSON] parsed json response from handle server
72
+ #
73
+ def delete_it(path)
74
+ url = @base_url + path
75
+ json = self.class.delete(url, options).parsed_response
76
+ check_errors(json)
77
+ json
78
+ end
79
+
80
+ private
81
+
82
+ #
83
+ # Header and connection options
84
+ #
85
+ # @raise HandleSystem::Error
86
+ # @return [Hash]
87
+ #
88
+ def options
89
+ {
90
+ headers: {
91
+ 'Content-Type': 'application/json;charset=UTF-8',
92
+ 'Authorization': 'Handle sessionId="' + @session_id + '"'
93
+ },
94
+ verify: false
95
+ }
96
+ end
97
+
98
+ #
99
+ # If we got an error message from the handle server, convert it into
100
+ # an actual exception and throw it here
101
+ #
102
+ # @param [JSON] json handle server json response
103
+ # @raise HandleSystem::Error
104
+ #
105
+ def check_errors(json)
106
+ return unless json['message']
107
+
108
+ raise Error.new(json['responseCode'], json['handle'], json['message'])
109
+ end
110
+
111
+ #
112
+ # Initialize a new session with the handle server using its
113
+ # challenge-response framework
114
+ #
115
+ # @raise AuthenticationError if identity not verified
116
+ #
117
+ # @return [String] the authenticated session id
118
+ #
119
+ def initialize_session
120
+ # get initial challenge from handle server
121
+ url = @base_url + '/sessions/'
122
+ json = self.class.post(url, verify: false).parsed_response
123
+ nounce = Base64.decode64(json['nonce'])
124
+ session_id = json['sessionId']
125
+
126
+ # create authorization header
127
+ headers = {
128
+ 'Content-Type': 'application/json;charset=UTF-8',
129
+ 'Authorization': create_auth_header(nounce, session_id)
130
+ }
131
+
132
+ # send it back to handle server to get authenticated session id
133
+ opts = { headers: headers, verify: false }
134
+ json = self.class.put(url + 'this', opts).parsed_response
135
+ raise AuthenticationError, json['error'] unless json['authenticated']
136
+
137
+ json['sessionId']
138
+ end
139
+
140
+ #
141
+ # Create authentication header
142
+ #
143
+ # @param [String] server_nonce nonce from handle server
144
+ # @param [String] session_id session identifier from handle server
145
+ #
146
+ # @return [String] handle authorization header
147
+ #
148
+ def create_auth_header(server_nonce, session_id)
149
+ # challenge response is combination of server's nonce and
150
+ # client nonce that we will create ourselves
151
+ client_nonce = SecureRandom.random_bytes(16)
152
+ combined_nonce = server_nonce + client_nonce
153
+
154
+ # create combined nonce digest and sign with private key
155
+ private_key = OpenSSL::PKey::RSA.new(File.read(@private_key_path))
156
+ signature = private_key.sign(OpenSSL::Digest::SHA256.new, combined_nonce)
157
+
158
+ # build the authorization header
159
+ header = 'Handle sessionId="' + session_id + '", ' \
160
+ 'id="' + CGI.escape(@hs_admin) + '", ' \
161
+ 'type="HS_PUBKEY", ' \
162
+ 'cnonce="' + Base64.encode64(client_nonce) + '", ' \
163
+ 'alg="SHA256", ' \
164
+ 'signature="' + Base64.encode64(signature) + '"'
165
+ header.gsub("\n", '')
166
+ end
167
+ end
168
+ end
@@ -0,0 +1,149 @@
1
+ # frozen_string_literal: true
2
+
3
+ module HandleSystem
4
+ #
5
+ # Handle Record entry
6
+ #
7
+ # @author David Walker
8
+ #
9
+ class Record
10
+ # @return [Hash] the internal hash data
11
+ attr_reader :data
12
+
13
+ # @return [String] handle identifier
14
+ attr_reader :handle
15
+
16
+ # @return [String] the url we registered
17
+ attr_reader :url
18
+
19
+ # @return [String] email address added to record
20
+ attr_reader :email
21
+
22
+ # @return [String] handle administrator
23
+ attr_reader :hs_admin
24
+
25
+ #
26
+ # Populate Record from values
27
+ #
28
+ # @param [String] handle e.g., 20.500.12345/876
29
+ # @param [String] url the url we want to register
30
+ # @param [String] email [optional] email address to add to record
31
+ # @param [String] hs_admin [optional] handle administrator to add to record
32
+ #
33
+ def from_values(handle, url, email = nil, hs_admin = nil)
34
+ @handle = handle
35
+ @url = url
36
+ @email = email
37
+ @hs_admin = hs_admin
38
+
39
+ values = [build_url_field(url)]
40
+ values.push(build_email_field(email)) unless email.nil?
41
+ values.push(build_admin_field(hs_admin)) unless hs_admin.nil?
42
+ @data = {
43
+ 'values': values,
44
+ 'handle': handle,
45
+ 'responseCode': 1
46
+ }
47
+ self
48
+ end
49
+
50
+ #
51
+ # Populate Record from JSON
52
+ #
53
+ # @param [JSON] data the handle server record as json
54
+ #
55
+ def from_json(json)
56
+ @data = json
57
+ @handle = json['handle']
58
+ json['values'].each do |part|
59
+ value = part['data']['value']
60
+ @url = value if part['type'] == 'URL'
61
+ @has_admin = value if part['type'] == 'EMAIL'
62
+ @email = value if part['type'] == 'HS_ADMIN'
63
+ end
64
+ self
65
+ end
66
+
67
+ #
68
+ # @return [<String>] JSON string
69
+ #
70
+ def json
71
+ @data.to_json
72
+ end
73
+
74
+ private
75
+
76
+ #
77
+ # Current date-time
78
+ #
79
+ # @return [String]
80
+ #
81
+ def timestamp
82
+ DateTime.now.strftime('%Y-%m-%dT%H:%M:%SZ')
83
+ end
84
+
85
+ #
86
+ # Create a new URL field
87
+ #
88
+ # @param [String] url the url we want to register
89
+ #
90
+ # @return [Hash]
91
+ #
92
+ def build_url_field(url)
93
+ {
94
+ 'index': 1,
95
+ 'ttl': 86_400,
96
+ 'type': 'URL',
97
+ 'timestamp': timestamp,
98
+ 'data': {
99
+ 'value': url,
100
+ 'format': 'string'
101
+ }
102
+ }
103
+ end
104
+
105
+ #
106
+ # Create a new EMAIL field
107
+ #
108
+ # @param [String] email email address
109
+ #
110
+ # @return [Hash]
111
+ #
112
+ def build_email_field(email)
113
+ {
114
+ 'index': 2,
115
+ 'ttl': 86_400,
116
+ 'type': 'EMAIL',
117
+ 'timestamp': timestamp,
118
+ 'data': {
119
+ 'value': email,
120
+ 'format': 'string'
121
+ }
122
+ }
123
+ end
124
+
125
+ #
126
+ # Create a new HS_ADMIN field
127
+ #
128
+ # @param [String] hs_admin handle administrator
129
+ #
130
+ # @return [Hash]
131
+ #
132
+ def build_admin_field(hs_admin)
133
+ {
134
+ 'index': 100,
135
+ 'ttl': 86_400,
136
+ 'type': 'HS_ADMIN',
137
+ 'timestamp': timestamp,
138
+ 'data': {
139
+ 'value': {
140
+ 'index': 200,
141
+ 'handle': hs_admin,
142
+ 'permissions': '011111110011'
143
+ },
144
+ 'format': 'admin'
145
+ }
146
+ }
147
+ end
148
+ end
149
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module HandleSystem
4
+ VERSION = '0.1.1'
5
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'handle_system/client'
5
+ require 'handle_system/exceptions'
6
+ require 'handle_system/http_client'
7
+ require 'handle_system/record'
metadata ADDED
@@ -0,0 +1,92 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: handle-system-rest
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - David Walker
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2020-05-18 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: httparty
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '0.18'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '0.18'
27
+ - !ruby/object:Gem::Dependency
28
+ name: solargraph
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ description: A library for interfacing with the Handle System JSON REST API. This
42
+ gem works with Handle System version 8 or higher. For older versions of the Handle
43
+ System, which didn't have a JSON API, consider using the handle-system gem
44
+ email:
45
+ - dwalker@calstate.edu
46
+ executables: []
47
+ extensions: []
48
+ extra_rdoc_files: []
49
+ files:
50
+ - ".gitignore"
51
+ - ".rspec"
52
+ - ".travis.yml"
53
+ - Gemfile
54
+ - LICENSE.txt
55
+ - README.md
56
+ - Rakefile
57
+ - bin/console
58
+ - bin/setup
59
+ - handle_system.gemspec
60
+ - lib/handle_system.rb
61
+ - lib/handle_system/client.rb
62
+ - lib/handle_system/exceptions.rb
63
+ - lib/handle_system/http_client.rb
64
+ - lib/handle_system/record.rb
65
+ - lib/handle_system/version.rb
66
+ homepage: https://github.com/csuscholarworks/handle-system
67
+ licenses:
68
+ - APACHE
69
+ metadata:
70
+ homepage_uri: https://github.com/csuscholarworks/handle-system
71
+ source_code_uri: https://github.com/csuscholarworks/handle-system
72
+ changelog_uri: https://github.com/csuscholarworks/handle-system/README.md
73
+ post_install_message:
74
+ rdoc_options: []
75
+ require_paths:
76
+ - lib
77
+ required_ruby_version: !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - ">="
80
+ - !ruby/object:Gem::Version
81
+ version: 2.5.0
82
+ required_rubygems_version: !ruby/object:Gem::Requirement
83
+ requirements:
84
+ - - ">="
85
+ - !ruby/object:Gem::Version
86
+ version: '0'
87
+ requirements: []
88
+ rubygems_version: 3.0.6
89
+ signing_key:
90
+ specification_version: 4
91
+ summary: A library for interfacing with the Handle System JSON REST API.
92
+ test_files: []