1
|
module LdapOuToGroup
|
2
|
module InstanceMethods
|
3
|
def authenticate_with_sync_ou_to_group(login, password)
|
4
|
result = authenticate_without_sync_ou_to_group(login, password)
|
5
|
return nil unless result
|
6
|
attrs = get_user_dn(login, password)
|
7
|
if (user = User.find_by_login(login))
|
8
|
ous = parse_ou_from_dn(attrs[:dn])
|
9
|
sync_ou_to_group(user, ous)
|
10
|
end
|
11
|
attrs
|
12
|
end
|
13
|
|
14
|
def parse_ou_from_dn(str)
|
15
|
# The str looks like the following line
|
16
|
# CN=zhangyi,OU=研发平台,OU=流程管理,OU=FFFF,OU=研发中心,OU=MMMM,DC=MMMMM,DC=com
|
17
|
str.split(/,\s*/).select{|i| i =~ /^OU=.+$/}.map{|s| s[3, s.size]}
|
18
|
end
|
19
|
|
20
|
def sync_ou_to_group(user, ous)
|
21
|
member_of_groups = user.groups.map{|g|g.name}
|
22
|
ous.each do |ou|
|
23
|
next if member_of_groups.include?(ou)
|
24
|
group = try_to_create_group_from_ou(ou)
|
25
|
user.groups << group
|
26
|
end
|
27
|
end
|
28
|
|
29
|
def try_to_create_group_from_ou(ou)
|
30
|
unless (g = Group.find_by_lastname(ou))
|
31
|
g = Group.new
|
32
|
g.lastname = ou
|
33
|
g.auth_source_id = self.id
|
34
|
g.save!
|
35
|
end
|
36
|
g
|
37
|
end
|
38
|
end
|
39
|
|
40
|
def self.included(receiver)
|
41
|
receiver.send(:include, InstanceMethods)
|
42
|
receiver.send(:alias_method_chain, :authenticate, :sync_ou_to_group)
|
43
|
end
|
44
|
end
|