psu_dir 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 38f15c203dbe7e880535a394e06e6cece1299fe19294054e81b12ff531459ffa
4
+ data.tar.gz: 924167e4aa0e213a501bcab5b8d9b5734029bf79539408b2839d370e0e720f60
5
+ SHA512:
6
+ metadata.gz: b412309069f1e42f9d6a53d1bb2374ae365610265233dde4a285b9c9b5a73611d453f2c3867bfc543848dbb7e089b7ad433a46d45bd5e77cadac92e8cbdd994e
7
+ data.tar.gz: 6e74c9007572462b57df8e569c72f1643ccb44ce0e286b0480f705cfdda5c782895b877548f05736dbe4b1f983edf037840327b968d9f96a5e6eab3a4c5ecc71
@@ -0,0 +1,13 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
12
+ Gemfile.lock
13
+ config/hydra-ldap.yml
data/.rspec ADDED
@@ -0,0 +1,5 @@
1
+ --color
2
+ --tty
3
+ --format progress
4
+ --profile
5
+ --require spec_helper
@@ -0,0 +1,4 @@
1
+ inherit_from: .rubocop_todo.yml
2
+
3
+ inherit_gem:
4
+ niftany: niftany_rubocop.yml
@@ -0,0 +1,35 @@
1
+ # This configuration was generated by
2
+ # `rubocop --auto-gen-config`
3
+ # on 2018-05-15 10:32:26 -0400 using RuboCop version 0.52.1.
4
+ # The point is for the user to remove these configuration records
5
+ # one by one as the offenses are removed from the code base.
6
+ # Note that changes in the inspected code, or installation of new
7
+ # versions of RuboCop, may require this file to be generated again.
8
+
9
+ # Offense count: 7
10
+ # Configuration parameters: CountComments, ExcludedMethods.
11
+ Metrics/BlockLength:
12
+ Max: 170
13
+
14
+ # Offense count: 9
15
+ # Configuration parameters: .
16
+ # SupportedStyles: have_received, receive
17
+ RSpec/MessageSpies:
18
+ EnforcedStyle: receive
19
+
20
+ # Offense count: 6
21
+ # Configuration parameters: AggregateFailuresByDefault.
22
+ RSpec/MultipleExpectations:
23
+ Max: 4
24
+
25
+ # Offense count: 6
26
+ # Configuration parameters: Max.
27
+ RSpec/NestedGroups:
28
+ Exclude:
29
+ - 'spec/psu_dir/ldap_user_spec.rb'
30
+
31
+ # Offense count: 60
32
+ # Configuration parameters: AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns.
33
+ # URISchemes: http, https
34
+ Metrics/LineLength:
35
+ Max: 279
@@ -0,0 +1,13 @@
1
+ language: ruby
2
+ cache:
3
+ bundler: true
4
+ rvm:
5
+ - 2.4.1
6
+ stages:
7
+ - rubocop
8
+ - test
9
+ jobs:
10
+ include:
11
+ - script: cp config/travis/hydra-ldap.yml config/hydra-ldap.yml && bundle exec rspec
12
+ - stage: rubocop
13
+ script: bundle exec rubocop
data/Gemfile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ git_source(:github) { |repo_name| "https://github.com/#{repo_name}" }
6
+
7
+ # Specify your gem's dependencies in psu_dir.gemspec
8
+ gemspec
@@ -0,0 +1,177 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,64 @@
1
+ # PsuDir
2
+
3
+ Directory services integrations at Penn State University.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'psu_dir'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install psu_dir
20
+
21
+ ## Usage
22
+
23
+ Instantiate the service with a string `PsuDir::Name.new("jbd123")` and then
24
+ call the disambiguate method which returns an array of people in the format `[{:id=>"jbd123", :given_name=>"Jane B", :surname=>"Doe", :email=>"jbd123@psu.edu", :affiliation=>["STAFF"]}]`
25
+
26
+ What you pass in as the name can vary from an id to a list of names and or emails.
27
+
28
+ ### Basic usage with a id
29
+
30
+ You can call disambiguate with an id, which then calls ldap and returns a record.
31
+
32
+ ```
33
+ service = PsuDir::Name.new("cam156") # #<PsuDir::Name:0x007fab36190710 @name="cam156", @email_for_name_cache={}, @results=[]>
34
+ service.disambiguate #[{:id=>"cam156", :given_name=>"CAROLYN A", :surname=>"COLE", :email=>"cam156@psu.edu", :affiliation=>["STAFF"]}]
35
+ ```
36
+
37
+ ### Basic usage with a name
38
+
39
+ ```
40
+ service = PsuDir::Name.new("Carolyn Cole") # #<PsuDir::Name:0x007fab36190710 @name="Carolyn Cole", @email_for_name_cache={}, @results=[]>
41
+ service.disambiguate #[{:id=>"cam156", :given_name=>"CAROLYN A", :surname=>"COLE", :email=>"cam156@psu.edu", :affiliation=>["STAFF"]}]
42
+ ```
43
+
44
+ ### Usage with last name and first name part
45
+ ```
46
+ service = PsuDir::Name.new("Carol Cole") # #<PsuDir::Name:0x007fab36190710 @name="Carol Cole", @email_for_name_cache={}, @results=[]>
47
+ service.disambiguate #[{:id=>"cam156", :given_name=>"CAROLYN A", :surname=>"COLE", :email=>"cam156@psu.edu", :affiliation=>["STAFF"]}]
48
+ ```
49
+
50
+ ### Usage with last name and first name part
51
+ ```
52
+ service = PsuDir::Name.new("Carol Cole, cam156") # #<PsuDir::Name:0x007fab36190710 @name="Carol Cole", @email_for_name_cache={}, @results=[]>
53
+ service.disambiguate #[{:id=>"cam156", :given_name=>"CAROLYN A", :surname=>"COLE", :email=>"cam156@psu.edu", :affiliation=>["STAFF"]}]
54
+ ```
55
+
56
+ ### Usage with a list of names
57
+ ```
58
+ service = PsuDir::Name.new("Carol Cole; Adam Wead") ##<PsuDir::Name:0x007fab32cf2418 @name="Carol Cole; Adam Wead", @email_for_name_cache={}, @results=[]>
59
+ service.disambiguate #[{:id=>"cam156", :given_name=>"CAROLYN A", :surname=>"COLE", :email=>"cam156@psu.edu", :affiliation=>["STAFF"]}, {:id=>"agw13", :given_name=>"ADAM GARNER", :surname=>"WEAD", :email=>"agw13@psu.edu", :affiliation=>["STAFF"]}]
60
+ ```
61
+
62
+ ## Contributing
63
+
64
+ Bug reports and pull requests are welcome!
@@ -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,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'bundler/setup'
5
+ require 'psu_dir'
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require 'irb'
15
+ IRB.start(__FILE__)
@@ -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,24 @@
1
+ development:
2
+ host: ldap.example.com
3
+ port: 389
4
+ # username: cn=admin,dc=example,dc=com
5
+ # password: simple77
6
+ group_base: dc=psu,dc=edu
7
+ base: dc=example,dc=com
8
+ uid: uid
9
+ test:
10
+ host: ldap.example.com
11
+ port: 389
12
+ # username: cn=admin,dc=example,dc=com
13
+ # password: simple77
14
+ group_base: dc=psu,dc=edu
15
+ # base: dc=example,dc=com
16
+ # uid: uid
17
+ production:
18
+ host: ldap.example.com
19
+ port: 389
20
+ #username: cn=admin,dc=example,dc=com
21
+ #password: <%= ENV['LDAP_PASSWORD'] %>
22
+ group_base: dc=psu,dc=edu
23
+ base: dc=example,dc=com
24
+ uid: uid
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'psu_dir/version'
4
+ require 'net-ldap'
5
+ require 'hydra-ldap'
6
+ require 'namae'
7
+ require 'logger'
8
+ require 'mail'
9
+
10
+ module PsuDir
11
+ autoload :Disambiguate, 'psu_dir/disambiguate'
12
+ autoload :LdapUser, 'psu_dir/ldap_user'
13
+ autoload :Ldap, 'psu_dir/ldap'
14
+
15
+ class << self
16
+ def logger
17
+ @logger ||= if Rails.try(:logger)
18
+ Rails.logger
19
+ else
20
+ Logger.new(STDOUT)
21
+ end
22
+ end
23
+
24
+ def ldap_unwilling_sleep
25
+ @ldap_unwilling_sleep ||= ENV.fetch('ldap_unwilling_sleep', 2).to_i
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PsuDir::Disambiguate
4
+ autoload :Base, 'psu_dir/disambiguate/base'
5
+ autoload :Name, 'psu_dir/disambiguate/name'
6
+ autoload :Email, 'psu_dir/disambiguate/email'
7
+ autoload :User, 'psu_dir/disambiguate/user'
8
+ autoload :MultipleUserError, 'psu_dir/disambiguate/multiple_user_error'
9
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PsuDir::Disambiguate
4
+ # This class allows you to use LDAP to disambiguate a text name
5
+ #
6
+ class Base
7
+ class << self
8
+ private
9
+
10
+ def ldap_attributes_for_id(id)
11
+ users = User.directory_attributes(id, ldap_attrs)
12
+ users.count < 1 ? nil : users
13
+ end
14
+
15
+ def ldap_attrs
16
+ %i[uid givenname sn mail eduPersonPrimaryAffiliation displayname]
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PsuDir::Disambiguate
4
+ # This class allows you to use LDAP to extract user information
5
+ # from an email or list of emails
6
+ #
7
+ class Email < Base
8
+ class << self
9
+ def disambiguate(email)
10
+ return unless email.include?('@psu.edu')
11
+ email_in_name(email)
12
+ end
13
+
14
+ private
15
+
16
+ def email_in_name(email_list)
17
+ parts = email_list.split(' ')
18
+ emails = parts.select { |part| part.include?('@') }
19
+ results = []
20
+ Array(emails).each do |email_str|
21
+ email = Mail::Address.new(email_str)
22
+ results << (ldap_attributes_for_id(email.local) || ldap_attributes_for_email(email.address) || [User.results_hash(mail: [email.address])]).first
23
+ end
24
+ results
25
+ end
26
+
27
+ def ldap_attributes_for_email(email)
28
+ users = User.query_ldap_by_mail(email, ldap_attrs)
29
+ users.count < 1 ? nil : users
30
+ end
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PsuDir::Disambiguate
4
+ # This error is thrown if we get more than one user back from ldap for an input
5
+ #
6
+ class MultipleUserError < RuntimeError
7
+ end
8
+ end
@@ -0,0 +1,125 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PsuDir::Disambiguate
4
+ # This class allows you to use LDAP to disambiguate a text name
5
+ #
6
+ class Name < Base
7
+ class << self
8
+ def disambiguate(name)
9
+ return if name.blank?
10
+ results = ldap_attributes_for_id(name) # text includes login id
11
+ results ||= Email.disambiguate(name) # text includes email(s)
12
+ results ||= lookup_text_only_names(name) # straight text we need to query ldap
13
+ results
14
+ end
15
+
16
+ def clear_cache
17
+ @email_for_name_cache = {}
18
+ end
19
+
20
+ private
21
+
22
+ def lookup_text_only_names(multi_name)
23
+ results = separate_names(multi_name).map do |name|
24
+ lookup_name(clean_name(name))
25
+ end
26
+ results.reject(&:blank?)
27
+ end
28
+
29
+ def lookup_name(name)
30
+ query_result = email_for_name(name)
31
+ query_result ||= title_after_name(name) # try again without the titles
32
+ query_result
33
+ rescue MultipleUserError
34
+ return nil
35
+ end
36
+
37
+ def email_for_name(text_name)
38
+ return '' if text_name.blank? || word_count(text_name) < 2
39
+ return email_for_name_cache[text_name] if email_for_name_cache.key?(text_name)
40
+
41
+ email_for_name_cache[text_name] = translate_name_to_email(text_name)
42
+ end
43
+
44
+ # titles after the name that namae had trouble parsing
45
+ def title_after_name(text_name)
46
+ email_for_name(remove_titles(text_name))
47
+ end
48
+
49
+ def translate_name_to_email(text_name)
50
+ parsed = Namae::Name.parse(text_name)
51
+
52
+ result = try_name(parsed.given, parsed.family)
53
+ result ||= title_before_name(parsed)
54
+ result ||= two_words_in_last_name(text_name)
55
+ result
56
+ end
57
+
58
+ def try_name(given, family)
59
+ return nil if family.blank?
60
+
61
+ possible_users = User.query_ldap_by_name(given, family, ldap_attrs)
62
+ raise(MultipleUserError, "too name results for #{given} #{family}") if possible_users.count > 1
63
+ possible_users.first
64
+ end
65
+
66
+ def title_before_name(parsed)
67
+ return unless parsed.given && multi_word?(parsed.given)
68
+
69
+ parts = name_parts(parsed.given, 1)
70
+ return if only_initial?(parts[:family])
71
+
72
+ try_name(parts[:family], parsed.family)
73
+ end
74
+
75
+ def two_words_in_last_name(text_name)
76
+ return unless word_count(text_name) > 2
77
+
78
+ parts = name_parts(text_name, 2)
79
+ try_name(parts[:given], parts[:family])
80
+ end
81
+
82
+ def name_parts(text_name, last_name_count)
83
+ return if word_count(text_name) < (last_name_count + 1)
84
+
85
+ parts = split_name_parts(text_name)
86
+ first_name_count = parts.count - last_name_count
87
+ { given: parts.first(first_name_count).join(' '), family: parts.last(last_name_count).join(' ') }
88
+ end
89
+
90
+ def clean_name(name)
91
+ name.gsub(/\([^)]*\)/, '')
92
+ .gsub(/[^\w\s,']/, ' ')
93
+ .strip.squeeze(' ')
94
+ end
95
+
96
+ def multi_word?(name)
97
+ word_count(name) > 1
98
+ end
99
+
100
+ def word_count(name)
101
+ name.squeeze(' ').count(' ') + 1
102
+ end
103
+
104
+ def split_name_parts(name)
105
+ name.split(' ')
106
+ end
107
+
108
+ def only_initial?(name)
109
+ name.size <= 1
110
+ end
111
+
112
+ def separate_names(multi_name)
113
+ multi_name.split(/ and |;/)
114
+ end
115
+
116
+ def remove_titles(name)
117
+ name.split(',')[0]
118
+ end
119
+
120
+ def email_for_name_cache
121
+ @email_for_name_cache ||= {}
122
+ end
123
+ end
124
+ end
125
+ end
@@ -0,0 +1,114 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PsuDir::Disambiguate
4
+ # This class provides an api for querying LDAP with different portions of the user's
5
+ # information (name parts or id)
6
+ class User < PsuDir::Ldap
7
+ class << self
8
+ def directory_attributes(login, attrs = [])
9
+ filter = Net::LDAP::Filter.eq('uid', login)
10
+ result = get_users(filter, attrs)
11
+ format_users(result, attrs)
12
+ end
13
+
14
+ def query_ldap_by_mail(email, attrs = [])
15
+ filter = Net::LDAP::Filter.construct(email_filter(email))
16
+ users = get_filtered_users(filter, attrs)
17
+ format_users(users, attrs)
18
+ end
19
+
20
+ def query_ldap_by_name(given_name, surname, attrs = [])
21
+ return [] if given_name.blank? # this method only work if we have a first name to play with
22
+
23
+ first_names = given_name.split(/[\s.]+/)
24
+ users = []
25
+ name_filters(first_names[0], first_names[1], surname).each do |filter|
26
+ users = get_filtered_users(filter, attrs)
27
+ break if users.count.positive? # stop running through the filters if we get results
28
+ end
29
+ format_users(users, attrs)
30
+ end
31
+
32
+ def get_filtered_users(name_filter, attrs = [])
33
+ attrs = (attrs + default_attributes).uniq
34
+ filter = Net::LDAP::Filter.construct("(& (& #{name_filter}) #{person_filter})")
35
+ get_users(filter, attrs)
36
+ end
37
+
38
+ def results_hash(opts)
39
+ {
40
+ id: fetch(opts, :uid).first,
41
+ given_name: fetch(opts, :givenname).first,
42
+ surname: fetch(opts, :sn).first,
43
+ email: fetch(opts, :mail).first,
44
+ affiliation: fetch(opts, :eduPersonPrimaryAffiliation, []),
45
+ displayname: fetch(opts, :displayname).first
46
+ }
47
+ end
48
+
49
+ private
50
+
51
+ def fetch(opts, key, default = [''])
52
+ opts[key].presence || default
53
+ end
54
+
55
+ def format_users(users, attrs)
56
+ user_attrs = attrs - default_attributes
57
+ users.map { |u| format_user(u, user_attrs) }
58
+ end
59
+
60
+ def format_user(user, extra_attrs)
61
+ hash = results_hash(user)
62
+ extra_attrs.each { |attr| hash[attr] = user[attr].first }
63
+ hash
64
+ end
65
+
66
+ def size_limit_exceeded?
67
+ Hydra::LDAP.connection.get_operation_result[:message] == 'Size Limit Exceeded'
68
+ end
69
+
70
+ def email_filter(email)
71
+ '(& (|'\
72
+ " (psmailid=#{email})"\
73
+ " (mail=#{email})"\
74
+ " (psmailbox=#{email})"\
75
+ " (edupersonprincipalname=#{email})"\
76
+ ") #{person_filter})"
77
+ end
78
+
79
+ def person_filter
80
+ '(|'\
81
+ ' (eduPersonPrimaryAffiliation=STUDENT)'\
82
+ ' (eduPersonPrimaryAffiliation=FACULTY)'\
83
+ ' (eduPersonPrimaryAffiliation=STAFF)'\
84
+ ' (eduPersonPrimaryAffiliation=EMPLOYEE)'\
85
+ ' (eduPersonPrimaryAffiliation=RETIREE)'\
86
+ ' (eduPersonPrimaryAffiliation=EMERITUS)'\
87
+ ' (eduPersonPrimaryAffiliation=MEMBER)'\
88
+ '))'
89
+ end
90
+
91
+ def name_filters(first_name, middle_name, surname)
92
+ filters = []
93
+ if middle_name.blank?
94
+ filters << "(givenname=#{first_name}) (sn=#{surname})"
95
+ filters << "(givenname=#{first_name}*) (sn=#{surname})"
96
+ else
97
+ filters << "(givenname=#{first_name}*) (givenname=* #{middle_name}*) (sn=#{surname})"
98
+ middle_initial = middle_name[0]
99
+ filters << "(givenname=#{first_name}* #{middle_initial}*) (sn=#{surname})"
100
+ end
101
+ filters << "(givenname=#{first_name}) (sn=#{surname})"
102
+ filters
103
+ end
104
+
105
+ def default_attributes
106
+ %i[uid givenname sn mail eduPersonPrimaryAffiliation displayname]
107
+ end
108
+
109
+ def cache
110
+ @cache ||= {}
111
+ end
112
+ end
113
+ end
114
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PsuDir
4
+ class Ldap
5
+ class << self
6
+ def get_users(filter, fields = [])
7
+ retry_if { Hydra::LDAP.get_user(filter, fields) } || []
8
+ end
9
+
10
+ # Retries the LDAP command up to .tries times, or catches any other kind of LDAP error without retrying.
11
+ # return [block or nil]
12
+ def retry_if
13
+ tries.times.each do
14
+ result = yield
15
+ return result unless unwilling?
16
+ sleep(PsuDir.ldap_unwilling_sleep)
17
+ end
18
+ PsuDir.logger.warn 'LDAP is unwilling to perform this operation, try upping the number of tries'
19
+ nil
20
+ rescue Net::LDAP::Error => e
21
+ PsuDir.logger.warn "Error getting LDAP response: #{ldap_error_message(e)}"
22
+ nil
23
+ end
24
+
25
+ def tries
26
+ 7
27
+ end
28
+
29
+ # Numeric code returned by LDAP if it is feeling "unwilling"
30
+ def unwilling?
31
+ Hydra::LDAP.connection.get_operation_result.code == 53
32
+ end
33
+
34
+ def ldap_error_message(e)
35
+ "#{Hydra::LDAP.connection.get_operation_result.message}\nException: #{e.exception}\n#{e.backtrace.join("\n")}"
36
+ end
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ class PsuDir::LdapUser < PsuDir::Ldap
4
+ class << self
5
+ def get_groups(login)
6
+ return [] if login.blank?
7
+ retry_if { parse_ldap_groups(group_response_from_ldap(login)) } || []
8
+ end
9
+
10
+ def check_ldap_exist!(login)
11
+ return false if login.blank?
12
+ retry_if { Hydra::LDAP.does_user_exist?(Net::LDAP::Filter.eq('uid', login)) } || false
13
+ end
14
+
15
+ def filter_for(*people)
16
+ return '' if people.empty?
17
+ '(| ' + people.map { |p| "(eduPersonPrimaryAffiliation=#{p.to_s.upcase})" }.join(' ') + ')))'
18
+ end
19
+
20
+ private
21
+
22
+ def parse_ldap_groups(result)
23
+ return [] if result.empty?
24
+ result.first[:psmemberof].select { |y| y.start_with? 'cn=umg/' }.map do |x|
25
+ x.sub(/^cn=/, '').sub(/,dc=psu,dc=edu/, '')
26
+ end
27
+ end
28
+
29
+ # Response from LDAP
30
+ # We have to pass a block, see https://github.com/projecthydra-labs/hydra-ldap/issues/8
31
+ def group_response_from_ldap(login)
32
+ Hydra::LDAP.groups_for_user(Net::LDAP::Filter.eq('uid', login)) { |r| r }
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PsuDir
4
+ VERSION = '0.1.0'
5
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ lib = File.expand_path('../lib', __FILE__)
4
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
5
+ require 'psu_dir/version'
6
+
7
+ Gem::Specification.new do |spec|
8
+ spec.name = 'psu_dir'
9
+ spec.version = PsuDir::VERSION
10
+ spec.authors = ['Carolyn Cole', 'Adam Wead']
11
+ spec.email = ['cam156@psu.edu', 'amsterdamos@gmail.com']
12
+
13
+ spec.summary = 'Directory services at Penn State University.'
14
+ spec.description = "Performs queries against Penn State's directory services to find users and return preferred"\
15
+ ' names, email address, and other information.'
16
+ spec.homepage = 'https://github.com/psu-stewardship/psu_dir'
17
+ spec.licenses = ['Apache-2.0']
18
+
19
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
20
+ spec.bindir = 'exe'
21
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
22
+ spec.require_paths = ['lib']
23
+
24
+ spec.add_dependency 'hydra-ldap'
25
+ spec.add_dependency 'mail', '~> 2.6'
26
+ spec.add_dependency 'namae', '0.9.3'
27
+ spec.add_dependency 'net-ldap', '~> 0.16.0'
28
+
29
+ spec.add_development_dependency 'bundler', '~> 1.16'
30
+ spec.add_development_dependency 'byebug', '~> 9.1'
31
+ spec.add_development_dependency 'niftany', '~> 0.0.2'
32
+ spec.add_development_dependency 'rake', '~> 10.0'
33
+ spec.add_development_dependency 'rspec', '~> 3.0'
34
+ spec.add_development_dependency 'rspec-its', '~> 1.2'
35
+ end
metadata ADDED
@@ -0,0 +1,210 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: psu_dir
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Carolyn Cole
8
+ - Adam Wead
9
+ autorequire:
10
+ bindir: exe
11
+ cert_chain: []
12
+ date: 2018-05-15 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: hydra-ldap
16
+ requirement: !ruby/object:Gem::Requirement
17
+ requirements:
18
+ - - ">="
19
+ - !ruby/object:Gem::Version
20
+ version: '0'
21
+ type: :runtime
22
+ prerelease: false
23
+ version_requirements: !ruby/object:Gem::Requirement
24
+ requirements:
25
+ - - ">="
26
+ - !ruby/object:Gem::Version
27
+ version: '0'
28
+ - !ruby/object:Gem::Dependency
29
+ name: mail
30
+ requirement: !ruby/object:Gem::Requirement
31
+ requirements:
32
+ - - "~>"
33
+ - !ruby/object:Gem::Version
34
+ version: '2.6'
35
+ type: :runtime
36
+ prerelease: false
37
+ version_requirements: !ruby/object:Gem::Requirement
38
+ requirements:
39
+ - - "~>"
40
+ - !ruby/object:Gem::Version
41
+ version: '2.6'
42
+ - !ruby/object:Gem::Dependency
43
+ name: namae
44
+ requirement: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - '='
47
+ - !ruby/object:Gem::Version
48
+ version: 0.9.3
49
+ type: :runtime
50
+ prerelease: false
51
+ version_requirements: !ruby/object:Gem::Requirement
52
+ requirements:
53
+ - - '='
54
+ - !ruby/object:Gem::Version
55
+ version: 0.9.3
56
+ - !ruby/object:Gem::Dependency
57
+ name: net-ldap
58
+ requirement: !ruby/object:Gem::Requirement
59
+ requirements:
60
+ - - "~>"
61
+ - !ruby/object:Gem::Version
62
+ version: 0.16.0
63
+ type: :runtime
64
+ prerelease: false
65
+ version_requirements: !ruby/object:Gem::Requirement
66
+ requirements:
67
+ - - "~>"
68
+ - !ruby/object:Gem::Version
69
+ version: 0.16.0
70
+ - !ruby/object:Gem::Dependency
71
+ name: bundler
72
+ requirement: !ruby/object:Gem::Requirement
73
+ requirements:
74
+ - - "~>"
75
+ - !ruby/object:Gem::Version
76
+ version: '1.16'
77
+ type: :development
78
+ prerelease: false
79
+ version_requirements: !ruby/object:Gem::Requirement
80
+ requirements:
81
+ - - "~>"
82
+ - !ruby/object:Gem::Version
83
+ version: '1.16'
84
+ - !ruby/object:Gem::Dependency
85
+ name: byebug
86
+ requirement: !ruby/object:Gem::Requirement
87
+ requirements:
88
+ - - "~>"
89
+ - !ruby/object:Gem::Version
90
+ version: '9.1'
91
+ type: :development
92
+ prerelease: false
93
+ version_requirements: !ruby/object:Gem::Requirement
94
+ requirements:
95
+ - - "~>"
96
+ - !ruby/object:Gem::Version
97
+ version: '9.1'
98
+ - !ruby/object:Gem::Dependency
99
+ name: niftany
100
+ requirement: !ruby/object:Gem::Requirement
101
+ requirements:
102
+ - - "~>"
103
+ - !ruby/object:Gem::Version
104
+ version: 0.0.2
105
+ type: :development
106
+ prerelease: false
107
+ version_requirements: !ruby/object:Gem::Requirement
108
+ requirements:
109
+ - - "~>"
110
+ - !ruby/object:Gem::Version
111
+ version: 0.0.2
112
+ - !ruby/object:Gem::Dependency
113
+ name: rake
114
+ requirement: !ruby/object:Gem::Requirement
115
+ requirements:
116
+ - - "~>"
117
+ - !ruby/object:Gem::Version
118
+ version: '10.0'
119
+ type: :development
120
+ prerelease: false
121
+ version_requirements: !ruby/object:Gem::Requirement
122
+ requirements:
123
+ - - "~>"
124
+ - !ruby/object:Gem::Version
125
+ version: '10.0'
126
+ - !ruby/object:Gem::Dependency
127
+ name: rspec
128
+ requirement: !ruby/object:Gem::Requirement
129
+ requirements:
130
+ - - "~>"
131
+ - !ruby/object:Gem::Version
132
+ version: '3.0'
133
+ type: :development
134
+ prerelease: false
135
+ version_requirements: !ruby/object:Gem::Requirement
136
+ requirements:
137
+ - - "~>"
138
+ - !ruby/object:Gem::Version
139
+ version: '3.0'
140
+ - !ruby/object:Gem::Dependency
141
+ name: rspec-its
142
+ requirement: !ruby/object:Gem::Requirement
143
+ requirements:
144
+ - - "~>"
145
+ - !ruby/object:Gem::Version
146
+ version: '1.2'
147
+ type: :development
148
+ prerelease: false
149
+ version_requirements: !ruby/object:Gem::Requirement
150
+ requirements:
151
+ - - "~>"
152
+ - !ruby/object:Gem::Version
153
+ version: '1.2'
154
+ description: Performs queries against Penn State's directory services to find users
155
+ and return preferred names, email address, and other information.
156
+ email:
157
+ - cam156@psu.edu
158
+ - amsterdamos@gmail.com
159
+ executables: []
160
+ extensions: []
161
+ extra_rdoc_files: []
162
+ files:
163
+ - ".gitignore"
164
+ - ".rspec"
165
+ - ".rubocop.yml"
166
+ - ".rubocop_todo.yml"
167
+ - ".travis.yml"
168
+ - Gemfile
169
+ - LICENSE.md
170
+ - README.md
171
+ - Rakefile
172
+ - bin/console
173
+ - bin/setup
174
+ - config/travis/hydra-ldap.yml
175
+ - lib/psu_dir.rb
176
+ - lib/psu_dir/disambiguate.rb
177
+ - lib/psu_dir/disambiguate/base.rb
178
+ - lib/psu_dir/disambiguate/email.rb
179
+ - lib/psu_dir/disambiguate/multiple_user_error.rb
180
+ - lib/psu_dir/disambiguate/name.rb
181
+ - lib/psu_dir/disambiguate/user.rb
182
+ - lib/psu_dir/ldap.rb
183
+ - lib/psu_dir/ldap_user.rb
184
+ - lib/psu_dir/version.rb
185
+ - psu_dir.gemspec
186
+ homepage: https://github.com/psu-stewardship/psu_dir
187
+ licenses:
188
+ - Apache-2.0
189
+ metadata: {}
190
+ post_install_message:
191
+ rdoc_options: []
192
+ require_paths:
193
+ - lib
194
+ required_ruby_version: !ruby/object:Gem::Requirement
195
+ requirements:
196
+ - - ">="
197
+ - !ruby/object:Gem::Version
198
+ version: '0'
199
+ required_rubygems_version: !ruby/object:Gem::Requirement
200
+ requirements:
201
+ - - ">="
202
+ - !ruby/object:Gem::Version
203
+ version: '0'
204
+ requirements: []
205
+ rubyforge_project:
206
+ rubygems_version: 2.7.6
207
+ signing_key:
208
+ specification_version: 4
209
+ summary: Directory services at Penn State University.
210
+ test_files: []