Skip to content

Commit 0719bed

Browse files
author
blackhedd
committed
Added convenience methods and accessors so that authentication
and seach parameters can be specified more easily than by passing them in an argument hash.
1 parent 6205656 commit 0719bed

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

lib/net/ldap.rb

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,7 @@ class LdapError < Exception; end
284284
DefaultHost = "127.0.0.1"
285285
DefaultPort = 389
286286
DefaultAuth = {:method => :anonymous}
287+
DefaultTreebase = "dc=com"
287288

288289

289290
ResultStrings = {
@@ -322,6 +323,10 @@ def LDAP::result2string code # :nodoc:
322323
ResultStrings[code] || "unknown result (#{code})"
323324
end
324325

326+
327+
attr_accessor :host, :port, :base
328+
329+
325330
# Instantiate an object of type Net::LDAP to perform directory operations.
326331
# This constructor takes a Hash containing arguments. The following arguments
327332
# are supported:
@@ -340,13 +345,30 @@ def initialize args = {}
340345
@port = args[:port] || DefaultPort
341346
@verbose = false # Make this configurable with a switch on the class.
342347
@auth = args[:auth] || DefaultAuth
348+
@base = args[:base] || DefaultTreebase
343349

344350
# This variable is only set when we are created with LDAP::open.
345351
# All of our internal methods will connect using it, or else
346352
# they will create their own.
347353
@open_connection = nil
348354
end
349355

356+
# Convenient method to specify your authentication to the LDAP
357+
# server. Currently supports simple authentication requiring
358+
# a username and password. Observe that on most LDAP servers,
359+
# including A/D, the username is a complete DN.
360+
# require 'net/ldap'
361+
#
362+
# ldap = Net::LDAP.new
363+
# ldap.host = server_ip_address
364+
# ldap.authenticate "cn=Your Username,cn=Users,dc=example,dc=com", "your_psw"
365+
#
366+
def authenticate username, password
367+
@auth = {:method => :simple, :username => username, :password => password}
368+
end
369+
370+
alias_method :auth, :authenticate
371+
350372
# #open takes the same parameters as #new. #open makes a network connection to the
351373
# LDAP server and then passes a newly-created Net::LDAP object to the caller-supplied block.
352374
# Within the block, you can call any of the instance methods of Net::LDAP to
@@ -515,7 +537,8 @@ def searchx args
515537
# that the caller can set to suppress the return of a result set,
516538
# if he's planning to process every entry as it comes from the server.
517539
#
518-
def search args
540+
def search args = {}
541+
args[:base] ||= @base
519542
result_set = (args and args[:return_result] == false) ? nil : {}
520543

521544
if @open_connection

0 commit comments

Comments
 (0)