# # ldap_user.rb Ruby Module for read-only encapsulation of LDAP user entries # # Copyright (C) 2006 by Tilo Sloboda #-- # created: 29 Jan 2006 #++ # = Version # last modified: Time-stamp: # # = License: # Freely available under the terms of the OpenSource "Artistic License" # # = Description: # # QueryLDAP is for anonymous read-only LDAP-access only # # LDAP (aka Light-weight Directory Access Protocol) is designed # for applications where read-access is far more frequent than # write-access. Typically applications or clients bind (connect) # to LDAP anonymously for querying data. # Typically write-access to an LDAP-server is for a select group of system # administrators only. This module does not support write-access! # # This module implements anonymous read-only access to an LDAP-server's # people (or user) data -- mapping all the LDAP-attributes of a person's # LDAP-record to hash-entries in a LdapUser instance. # require 'ldap' # read-only encapsulation for an LDAP user record. # # All LDAP-attributes are mapped to a Hash and are accessible read-only # via the [] method # # You need to set @server and @base_dn before you can create new instances # LdapUser::server = "my-server.my-company.com" # LdapUser::base_dn = 'ou=people,dc=mycompany,dc=com" # class LdapUser < Hash @@server = 'ds.yourcompany.com' @@base_dn = 'ou=people,dc=yourcompany,dc=com' # @@connection = LDAP::Conn.new(@@server) # fully-qualified server name attr_accessor :server # your base DN, e.g. 'ou=people,dc=yourcompany,dc=com' attr_accessor :base_dn attr_reader :attributes attr_reader :exists? def disconnect @@connection = @@connection.unbind end def LdapUser.connect @@connection = LDAP::Conn.new(@@server) @@connection.simple_bind end def LdapUser.connected? puts @@connection.bound? @@connection.bound? end def LdapUser.error puts @@connection.perror end def exists? @exists end # get one specific user from LDAP and initialize # a new user instance with each of it's attributes # # returns an array of users def initialize(search) @attributes = Array.new LdapUser.connect if (! @@connection) or (! @@connection.bound?) result = @@connection.search2(@@base_dn, LDAP::LDAP_SCOPE_SUBTREE, search) @exists = false # raise an error if we get more than one result, one none raise "User doesn't exist in LDAP!" if result.size == 0 raise "Multiple LDAP-entries for this User-ID!?" if result.size > 1 @exists = true result[0].each do |key,val| @attributes.push(key) if val.class == Array val = '' if val.size == 0 val = val[0] if val.size == 1 # if it's an array with more than one entry, we keep the array end self[key] = val end end # class initialization LdapUser.connect end