Skip to content

Instantly share code, notes, and snippets.

@myobie
Created December 10, 2008 17:14
Show Gist options
  • Save myobie/34396 to your computer and use it in GitHub Desktop.
Save myobie/34396 to your computer and use it in GitHub Desktop.
class LdapServer
include DataMapper::Resource
property :id, Serial
property :host, String, :length => 255
property :port, Integer, :default => 389
property :base_dn, String, :length => 255, :default => "dc=example,dc=com"
property :object_class, String, :default => "organizationalPerson"
property :email_attr, String, :default => "mail"
property :name_attr, String, :default => "name"
# property :photo_attr, String
property :search_user, String, :length => 255
property :search_password, String, :length => 255
validates_present :host, :port, :base_dn, :object_class, :email_attr, :name_attr, :search_user, :search_password
def authenticate_as(email, password)
ldap = new_connection
ldap.bind_as(:base => base_dn, :filter => filter(:email => email), :attributes => 'dn', :password => password)
end
def get(hash)
ldap = new_connection
result = all(hash)
result.first
end
def import(email)
me = get(:email => email)
LdapUser.create(:email => me[email_attr], :name => me[name_attr])
end
def all(hash = {})
ldap = new_connection
ldap.search(:base => base_dn, :filter => filter(hash), :attributes => ['dn', email_attr, name_attr, 'objectclass'])
end
protected
def filter(hash = {})
f = Net::LDAP::Filter.eq('objectclass', object_class)
if hash[:email]
f = f & Net::LDAP::Filter.eq(email_attr, hash[:email])
end
if hash[:name]
f = f & Net::LDAP::Filter.eq(name_attr, hash[:name])
end
if hash[:dn]
f = f & Net::LDAP::Filter.eq('dn', hash[:dn])
end
f
end
def new_connection
@connection ||= lambda {
ldap = Net::LDAP.new
ldap.host = host
ldap.auth search_user, search_password
ldap
}.call
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment