Loading users from Active Directory into a Rails 3.1 Active Record database
Update 11/30/11 I made some changes in the code snippet where I found errors. I am now successfully authenticating for sure, but am getting this error after attempting the ldap.search call:
<OpenStruct code = 1, message="Operations Error">
Using Rails 3.1.0 and ruby 1.9.2 on Windows Server 2008 R2
Original Message I'm brand new to Ruby, rails and programming. I have an application that will have to authenticate to our Active Directory server while maintaining a list of users separate from AD.
I'm attempting to use net-ldap to establish the connection, search AD and load the users, but I get 0 results with each attempt to run.
I've put this together based on samples I've seen, but when I customize it to my company, it doesn't seem to work. Any ideas/critiques are most welcome.
I've set this as a method in my User class model:
class User < ActiveRecord::Base attr_accessible :username, :name, :email, :team, :office, :points_attributes validates_presence_of :username, :name, :email validates_uniqueness_of :username, :email has_one :points accepts_nested_attributes_for :points def self.import_all # initialization stuff. set bind_dn, bind_pass, ldap_host, base_dn and filter ldap = Net::LDAP.new(:host => "dc.mycompany.com", :port => 389) if ldap.bind(:method => :simple, :username => "firstname.lastname@example.org", :password => "secret") else p ldap.get_operation_result end begin # Build the list filter = Net::LDAP::Filter.eq("displayName", "J*") attrs = ["givenName", "sn", "physicalDeliveryOfficeName", "sAMAccountName"] records = new_records = 0 ldap.search(:base => "DC=mycompany,DC=com", :attributes => attrs, :filter => filter, :return_result => false) do |entry| name = entry.givenName.to_s.strip + " " + entry.sn.to_s.strip username = entry.sAMAccountName.to_s.strip email = entry.sAMAccountName.to_s.strip + "@mycompany.com" office = entry.physicalDeliveryOfficeName.to_s.strip user = User.find_or_initialize_by_username :name => name, :username => username, :email => email, :office => office if user.new_record? user.save Points.find_or_create_by_user_id(user.id) new_records = new_records + 1 else user.touch end records = records + 1 end p ldap.get_operation_result logger.info( "LDAP Import Complete: " + Time.now.to_s ) logger.info( "Total Records Processed: " + records.to_s ) logger.info( "New Records: " + new_records.to_s ) end end end
It turns out that the error I'm getting is due to some of the attributes I'm searching for not existing on all the users under the tree I'm looking at.
Thanks to any that looked at this, but I believe I can move on to resolving how to handle entries without those attributes.