ldapimport.rb

Thimios Dimopulos, 2009-11-10 20:52

Download (2.57 KB)

 
1
@auth_method = AuthSourceLdap.find(1)
2
class AuthSourceLdap
3
  def import
4
    ldap_con = initialize_ldap_con(self.account, self.account_password)
5
    
6
    search_filter = Net::LDAP::Filter.eq("objectClass", "user")
7
    
8
    found = created = 0
9
    skipped = []
10
    ldap_con.search(
11
        :base => self.base_dn,
12
        :filter => search_filter,
13
        :attributes => ['dn', self.attr_firstname, self.attr_lastname, self.attr_mail, self.attr_login]
14
        ) do | entry |
15
            logger.debug("Found entry with DN: #{entry.dn}") if logger
16
            found += 1
17
            skip = false
18
            attrs = [:firstname => (AuthSourceLdap.get_attr(entry, self.attr_firstname) != nil ? \
19
                                    AuthSourceLdap.get_attr(entry, self.attr_firstname) : "Unknown"),
20
                     :lastname => AuthSourceLdap.get_attr(entry, self.attr_lastname),
21
                     :mail => AuthSourceLdap.get_attr(entry, self.attr_mail),
22
                     :auth_source_id => self.id ]
23
            #sanity checking (all the above attributes are required)
24
            login = AuthSourceLdap.get_attr(entry, self.attr_login)
25
            catch :SKIP do
26
              skip = false
27
              attrs.each { |e| 
28
                e.each { |k, v|
29
                  if v == nil
30
                    # give the admin a clue why importing failed...
31
                    logger.debug("User #{login} misses value for attribute '#{k}'.")
32
                    skipped.push(login+"(missing attribute '#{k}')")
33
                    skip = true
34
                    throw :SKIP
35
                  end
36
                }
37
              }
38
            end
39
            next if skip
40
            if User.find(:first, :conditions => ["login=?", login])
41
              logger.debug("User #{login} already there, skipping...") if logger
42
              skipped.push(login+'(exists)')
43
              next
44
            end
45
         
46
            #create user
47
            begin
48
              logger.debug("Trying to create user with attrs: %s" % attrs.to_s) if logger
49
              u = User.create(*attrs)
50
              u.login = login
51
              u.language = Setting.default_language
52
              if u.save
53
                created += 1
54
              else
55
                skipped.push(login+'(add failed)')
56
              end
57
            end
58
        end
59
        logger.info("Found #{found} users, imported #{created}.")
60
        logger.info("Skipped users: #{skipped.join(" ")}")
61
        return {:found => found, :imported => created, :skipped => skipped}
62
  end
63
end
64

    
65

    
66

    
67
@auth_method.import
68