Class: ActiveDirectory::Base
- Inherits:
-
Object
- Object
- ActiveDirectory::Base
- Defined in:
- lib/active_directory/base.rb
Overview
Base class for all Ruby/ActiveDirectory Entry Objects (like User and Group)
Constant Summary collapse
- NIL_FILTER =
A Net::LDAP::Filter object that doesn’t do any filtering (outside of check that the CN attribute is present. This is used internally for specifying a ‘no filter’ condition for methods that require a filter object.
Net::LDAP::Filter.pres('cn')
- @@ldap =
nil
- @@ldap_connected =
false
- @@caching =
false
- @@cache =
{}
Class Method Summary collapse
-
.cache? ⇒ Boolean
Check to see if result caching is enabled.
-
.class_name ⇒ Object
Pull the class we’re in This isn’t quite right, as extending the object does funny things to how we lookup objects.
-
.clear_cache ⇒ Object
Clears the cache.
-
.connected? ⇒ Boolean
Check to see if we are connected to the LDAP server This method will try to connect, if we haven’t already.
-
.create(dn, attributes) ⇒ Object
Create a new entry in the Active Record store.
-
.decode_field(name, value) ⇒ Object
:nodoc:.
-
.disable_cache ⇒ Object
Disable caching.
-
.enable_cache ⇒ Object
Enable caching for queries against the DN only This is to prevent membership lookups from hitting the AD unnecessarilly.
-
.encode_field(name, value) ⇒ Object
:nodoc:.
- .error ⇒ Object
-
.error? ⇒ Boolean
Check to see if the last query produced an error Note: Invalid username/password combinations will not produce errors.
-
.error_code ⇒ Object
Return the last errorcode that ldap generated.
-
.exists?(filter_as_hash) ⇒ Boolean
Check to see if any entries matching the passed criteria exists.
-
.filter ⇒ Object
:nodoc:.
-
.find(*args) ⇒ Object
Performs a search on the Active Directory store, with similar syntax to the Rails ActiveRecord#find method.
- .find_all(options) ⇒ Object
-
.find_cached_results(filters) ⇒ Object
Searches the cache and returns the result Returns false on failure, nil on wrong object type.
- .find_first(options) ⇒ Object
-
.get_field_type(name) ⇒ Object
Grabs the field type depending on the class it is called from Takes the field name as a parameter.
-
.make_filter(key, value) ⇒ Object
Makes a single filter from a given key and value It will try to encode an array if there is a process for it Otherwise, it will treat it as an or condition.
-
.make_filter_from_hash(hash) ⇒ Object
:nodoc:.
-
.method_missing(name, *args) ⇒ Object
:nodoc:.
-
.parse_finder_spec(method_name) ⇒ Object
:nodoc:.
-
.required_attributes ⇒ Object
:nodoc:.
-
.setup(settings) ⇒ Object
Configures the connection for the Ruby/ActiveDirectory library.
Instance Method Summary collapse
-
#==(other) ⇒ Object
:nodoc:.
-
#changed? ⇒ Boolean
Whether or not the entry has local changes that have not yet been replicated to the Active Directory server via a call to Base#save.
-
#destroy ⇒ Object
Deletes the entry from the Active Record store and returns true if the operation was successfully.
- #get_attr(name) ⇒ Object (also: #[])
-
#initialize(attributes = {}) ⇒ Base
constructor
FIXME: Need to document the Base::new.
-
#method_missing(name, args = []) ⇒ Object
:nodoc:.
-
#move(new_rdn) ⇒ Object
This method may one day provide the ability to move entries from container to container.
-
#new_record? ⇒ Boolean
Returns true if this entry does not yet exist in Active Directory.
-
#reload ⇒ Object
Refreshes the attributes for the entry with updated data from the domain controller.
-
#save ⇒ Object
Saves any pending changes to the entry by updating the remote entry.
- #set_attr(name, value) ⇒ Object (also: #[]=)
-
#to_ary ⇒ Object
Weird fluke with flattening, probably because of above attribute.
-
#update_attribute(name, value) ⇒ Object
Updates a single attribute (name) with one or more values (value), by immediately contacting the Active Directory server and initiating the update remotely.
-
#update_attributes(attributes_to_update) ⇒ Object
Updates multiple attributes, like ActiveRecord#update_attributes.
- #valid_attribute?(name) ⇒ Boolean
Constructor Details
#initialize(attributes = {}) ⇒ Base
FIXME: Need to document the Base::new
488 489 490 491 492 493 494 495 496 |
# File 'lib/active_directory/base.rb', line 488 def initialize(attributes = {}) # :nodoc: if attributes.is_a? Net::LDAP::Entry @entry = attributes @attributes = {} else @entry = nil @attributes = attributes end end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, args = []) ⇒ Object
:nodoc:
569 570 571 572 573 574 575 576 577 578 579 |
# File 'lib/active_directory/base.rb', line 569 def method_missing(name, args = []) # :nodoc: name = name.to_s.downcase return set_attr(name.chop, args) if name[-1] == '=' if valid_attribute? name.to_sym get_attr(name) else super end end |
Class Method Details
.cache? ⇒ Boolean
Check to see if result caching is enabled
103 104 105 |
# File 'lib/active_directory/base.rb', line 103 def self.cache? @@caching end |
.class_name ⇒ Object
Pull the class we’re in This isn’t quite right, as extending the object does funny things to how we lookup objects
502 503 504 |
# File 'lib/active_directory/base.rb', line 502 def self.class_name @klass ||= (self.name.include?('::') ? self.name[/.*::(.*)/, 1] : self.name) end |
.clear_cache ⇒ Object
Clears the cache
109 110 111 |
# File 'lib/active_directory/base.rb', line 109 def self.clear_cache @@cache = {} end |
.connected? ⇒ Boolean
Check to see if we are connected to the LDAP server This method will try to connect, if we haven’t already
92 93 94 95 96 97 98 99 |
# File 'lib/active_directory/base.rb', line 92 def self.connected? begin @@ldap_connected ||= @@ldap.bind unless @@ldap.nil? @@ldap_connected rescue Net::LDAP::LdapError => e false end end |
.create(dn, attributes) ⇒ Object
Create a new entry in the Active Record store.
dn is the Distinguished Name for the new entry. This must be a unique identifier, and can be passed as either a Container or a plain string.
attributes is a symbol-keyed hash of attribute_name => value pairs.
415 416 417 418 419 420 421 422 423 424 425 426 427 |
# File 'lib/active_directory/base.rb', line 415 def self.create(dn,attributes) return nil if dn.nil? || attributes.nil? begin attributes.merge!(required_attributes) if @@ldap.add(:dn => dn.to_s, :attributes => attributes) return find_by_distinguishedName(dn.to_s) else return nil end rescue return nil end end |
.decode_field(name, value) ⇒ Object
:nodoc:
518 519 520 521 522 523 524 |
# File 'lib/active_directory/base.rb', line 518 def self.decode_field(name, value) # :nodoc: type = get_field_type name if !type.nil? and ::ActiveDirectory::FieldType::const_defined? type return ::ActiveDirectory::FieldType::const_get(type).decode(value) end return value end |
.disable_cache ⇒ Object
Disable caching
123 124 125 |
# File 'lib/active_directory/base.rb', line 123 def self.disable_cache @@caching = false end |
.enable_cache ⇒ Object
Enable caching for queries against the DN only This is to prevent membership lookups from hitting the AD unnecessarilly
117 118 119 |
# File 'lib/active_directory/base.rb', line 117 def self.enable_cache @@caching = true end |
.encode_field(name, value) ⇒ Object
:nodoc:
526 527 528 529 530 531 532 |
# File 'lib/active_directory/base.rb', line 526 def self.encode_field(name, value) # :nodoc: type = get_field_type name if !type.nil? and ::ActiveDirectory::FieldType::const_defined? type return ::ActiveDirectory::FieldType::const_get(type).encode(value) end return value end |
.error ⇒ Object
71 72 73 |
# File 'lib/active_directory/base.rb', line 71 def self.error "#{@@ldap.get_operation_result.code}: #{@@ldap.get_operation_result.}" end |
.error? ⇒ Boolean
Check to see if the last query produced an error Note: Invalid username/password combinations will not produce errors
85 86 87 |
# File 'lib/active_directory/base.rb', line 85 def self.error? @@ldap.nil? ? false : @@ldap.get_operation_result.code != 0 end |
.error_code ⇒ Object
Return the last errorcode that ldap generated
77 78 79 |
# File 'lib/active_directory/base.rb', line 77 def self.error_code @@ldap.get_operation_result.code end |
.exists?(filter_as_hash) ⇒ Boolean
Check to see if any entries matching the passed criteria exists.
Filters should be passed as a hash of attribute_name => expected_value, like:
User.exists?(
:sn => 'Hunt',
:givenName => 'James'
)
which will return true if one or more User entries have an sn (surname) of exactly ‘Hunt’ and a givenName (first name) of exactly ‘James’.
Partial attribute matches are available. For instance,
Group.exists?(
:description => 'OldGroup_*'
)
would return true if there are any Group objects in Active Directory whose descriptions start with OldGroup_, like OldGroup_Reporting, or OldGroup_Admins.
Note that the * wildcard matches zero or more characters, so the above query would also return true if a group named ‘OldGroup_’ exists.
164 165 166 167 |
# File 'lib/active_directory/base.rb', line 164 def self.exists?(filter_as_hash) criteria = make_filter_from_hash(filter_as_hash) & filter (@@ldap.search(:filter => criteria).size > 0) end |
.filter ⇒ Object
:nodoc:
127 128 129 |
# File 'lib/active_directory/base.rb', line 127 def self.filter # :nodoc: NIL_FILTER end |
.find(*args) ⇒ Object
Performs a search on the Active Directory store, with similar syntax to the Rails ActiveRecord#find method.
The first argument passed should be either :first or :all, to indicate that we want only one (:first) or all (:all) results back from the resultant set.
The second argument should be a hash of attribute_name => expected_value pairs.
User.find(:all, :sn => 'Hunt')
would find all of the User objects in Active Directory that have a surname of exactly ‘Hunt’. As with the Base.exists? method, partial searches are allowed.
This method always returns an array if the caller specifies :all for the search e (first argument). If no results are found, the array will be empty.
If you call find(:first, …), you will either get an object (a User or a Group) back, or nil, if there were no entries matching your filter.
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 |
# File 'lib/active_directory/base.rb', line 233 def self.find(*args) return false unless connected? = { :filter => (args[1].nil?) ? NIL_FILTER : args[1], :in => '' } cached_results = find_cached_results(args[1]) return cached_results if cached_results or cached_results.nil? [:in] = [ [:in].to_s, @@settings[:base] ].delete_if { |part| part.empty? }.join(",") if [:filter].is_a? Hash [:filter] = make_filter_from_hash([:filter]) end [:filter] = [:filter] & filter unless self.filter == NIL_FILTER if (args.first == :all) find_all() elsif (args.first == :first) find_first() else raise ArgumentError, 'Invalid specifier (not :all, and not :first) passed to find()' end end |
.find_all(options) ⇒ Object
294 295 296 297 298 299 300 301 302 303 304 305 |
# File 'lib/active_directory/base.rb', line 294 def self.find_all() results = [] ldap_objs = @@ldap.search(:filter => [:filter], :base => [:in]) ldap_objs.each do |entry| ad_obj = new(entry) @@cache[entry.dn] = ad_obj unless ad_obj.instance_of? Base results << ad_obj end results end |
.find_cached_results(filters) ⇒ Object
Searches the cache and returns the result Returns false on failure, nil on wrong object type
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 |
# File 'lib/active_directory/base.rb', line 265 def self.find_cached_results(filters) return false unless cache? #Check to see if we're only looking for :distinguishedname return false unless filters.is_a? Hash and filters.keys == [:distinguishedname] #Find keys we're looking up dns = filters[:distinguishedname] if dns.kind_of? Array result = [] dns.each do |dn| entry = @@cache[dn] #If the object isn't in the cache just run the query return false if entry.nil? #Only permit objects of the type we're looking for result << entry if entry.kind_of? self end return result else return false unless @@cache.key? dns return @@cache[dns] if @@cache[dns].is_a? self end end |
.find_first(options) ⇒ Object
307 308 309 310 311 |
# File 'lib/active_directory/base.rb', line 307 def self.find_first() ad_obj = new(@@ldap.search(:filter => [:filter], :base => [:in])) @@cache[ad_obj.dn] = ad_obj unless ad_obj.instance_of? Base return ad_obj end |
.get_field_type(name) ⇒ Object
Grabs the field type depending on the class it is called from Takes the field name as a parameter
509 510 511 512 513 514 |
# File 'lib/active_directory/base.rb', line 509 def self.get_field_type(name) #Extract class name throw "Invalid field name" if name.nil? type = ::ActiveDirectory.special_fields[class_name.to_sym][name.to_s.downcase.to_sym] type.to_s unless type.nil? end |
.make_filter(key, value) ⇒ Object
Makes a single filter from a given key and value It will try to encode an array if there is a process for it Otherwise, it will treat it as an or condition
181 182 183 184 185 186 187 188 189 190 191 192 193 194 |
# File 'lib/active_directory/base.rb', line 181 def self.make_filter(key, value) #Join arrays using OR condition if value.is_a? Array filter = ~NIL_FILTER value.each do |v| filter |= Net::LDAP::Filter.eq(key, encode_field(key, v).to_s) end else filter = Net::LDAP::Filter.eq(key, encode_field(key, value).to_s) end return filter end |
.make_filter_from_hash(hash) ⇒ Object
:nodoc:
196 197 198 199 200 201 202 203 204 205 206 |
# File 'lib/active_directory/base.rb', line 196 def self.make_filter_from_hash(hash) # :nodoc: return NIL_FILTER if hash.nil? || hash.empty? filter = NIL_FILTER hash.each do |key, value| filter &= make_filter(key, value) end return filter end |
.method_missing(name, *args) ⇒ Object
:nodoc:
313 314 315 316 317 318 319 320 321 322 323 324 |
# File 'lib/active_directory/base.rb', line 313 def self.method_missing(name, *args) # :nodoc: name = name.to_s if (name[0,5] == 'find_') find_spec, attribute_spec = parse_finder_spec(name) raise ArgumentError, "find: Wrong number of arguments (#{args.size} for #{attribute_spec.size})" unless args.size == attribute_spec.size filters = {} [attribute_spec,args].transpose.each { |pr| filters[pr[0]] = pr[1] } find(find_spec, :filter => filters) else super name.to_sym, args end end |
.parse_finder_spec(method_name) ⇒ Object
:nodoc:
326 327 328 329 330 331 332 333 334 335 336 |
# File 'lib/active_directory/base.rb', line 326 def self.parse_finder_spec(method_name) # :nodoc: # FIXME: This is a prime candidate for a # first-class object, FinderSpec method_name = method_name.gsub(/^find_/,'').gsub(/^by_/,'first_by_') find_spec, attribute_spec = *(method_name.split('_by_')) find_spec = find_spec.to_sym attribute_spec = attribute_spec.split('_and_').collect { |s| s.to_sym } return find_spec, attribute_spec end |
.required_attributes ⇒ Object
:nodoc:
131 132 133 |
# File 'lib/active_directory/base.rb', line 131 def self.required_attributes # :nodoc: {} end |
.setup(settings) ⇒ Object
Configures the connection for the Ruby/ActiveDirectory library.
For example:
ActiveDirectory::Base.setup(
:host => 'domain_controller1.example.org',
:port => 389,
:base => 'dc=example,dc=org',
:auth => {
:username => '[email protected]',
:password => 'querying_users_password'
}
)
This will configure Ruby/ActiveDirectory to connect to the domain controller at domain_controller1.example.org, using port 389. The domain’s base LDAP dn is expected to be ‘dc=example,dc=org’, and Ruby/ActiveDirectory will try to bind as the [email protected] user, using the supplied password.
Currently, there can be only one active connection per execution context.
For more advanced options, refer to the Net::LDAP.new documentation.
66 67 68 69 |
# File 'lib/active_directory/base.rb', line 66 def self.setup(settings) @@settings = settings @@ldap = Net::LDAP.new(settings) end |
Instance Method Details
#==(other) ⇒ Object
:nodoc:
338 339 340 341 |
# File 'lib/active_directory/base.rb', line 338 def ==(other) # :nodoc: return false if other.nil? other[:objectguid] == get_attr(:objectguid) end |
#changed? ⇒ Boolean
Whether or not the entry has local changes that have not yet been replicated to the Active Directory server via a call to Base#save
173 174 175 |
# File 'lib/active_directory/base.rb', line 173 def changed? !@attributes.empty? end |
#destroy ⇒ Object
Deletes the entry from the Active Record store and returns true if the operation was successfully.
433 434 435 436 437 438 439 440 441 442 443 |
# File 'lib/active_directory/base.rb', line 433 def destroy return false if new_record? if @@ldap.delete(:dn => distinguishedName) @entry = nil @attributes = {} return true else return false end end |
#get_attr(name) ⇒ Object Also known as: []
538 539 540 541 542 543 544 545 546 547 548 549 550 |
# File 'lib/active_directory/base.rb', line 538 def get_attr(name) name = name.to_s.downcase return decode_field(name, @attributes[name.to_sym]) if @attributes.has_key?(name.to_sym) if @entry.attribute_names.include? name.to_sym value = @entry[name.to_sym] value = value.first if value.kind_of?(Array) && value.size == 1 value = value.to_s if value.nil? || value.size == 1 value = nil.to_s if value.empty? return self.class.decode_field(name, value) end end |
#move(new_rdn) ⇒ Object
This method may one day provide the ability to move entries from container to container. Currently, it does nothing, as we are waiting on the Net::LDAP folks to either document the Net::LDAP#modrdn method, or provide a similar method for moving / renaming LDAP entries.
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 |
# File 'lib/active_directory/base.rb', line 465 def move(new_rdn) return false if new_record? puts "Moving #{distinguishedName} to RDN: #{new_rdn}" settings = @@settings.dup settings[:port] = 636 settings[:encryption] = { :method => :simple_tls } ldap = Net::LDAP.new(settings) if ldap.rename( :olddn => distinguishedName, :newrdn => new_rdn, :delete_attributes => false ) return true else puts Base.error return false end end |
#new_record? ⇒ Boolean
Returns true if this entry does not yet exist in Active Directory.
346 347 348 |
# File 'lib/active_directory/base.rb', line 346 def new_record? @entry.nil? end |
#reload ⇒ Object
Refreshes the attributes for the entry with updated data from the domain controller.
354 355 356 357 358 359 |
# File 'lib/active_directory/base.rb', line 354 def reload return false if new_record? @entry = @@ldap.search(:filter => Net::LDAP::Filter.eq('distinguishedName',distinguishedName))[0] return !@entry.nil? end |
#save ⇒ Object
Saves any pending changes to the entry by updating the remote entry.
449 450 451 452 453 454 455 456 |
# File 'lib/active_directory/base.rb', line 449 def save if update_attributes(@attributes) @attributes = {} return true else return false end end |
#set_attr(name, value) ⇒ Object Also known as: []=
552 553 554 |
# File 'lib/active_directory/base.rb', line 552 def set_attr(name, value) @attributes[name.to_sym] = encode_field(name, value) end |
#to_ary ⇒ Object
Weird fluke with flattening, probably because of above attribute
565 566 |
# File 'lib/active_directory/base.rb', line 565 def to_ary end |
#update_attribute(name, value) ⇒ Object
Updates a single attribute (name) with one or more values (value), by immediately contacting the Active Directory server and initiating the update remotely.
Entries are always reloaded (via Base.reload) after calling this method.
369 370 371 |
# File 'lib/active_directory/base.rb', line 369 def update_attribute(name, value) update_attributes(name.to_s => value) end |
#update_attributes(attributes_to_update) ⇒ Object
Updates multiple attributes, like ActiveRecord#update_attributes. The updates are immediately sent to the server for processing, and the entry is reloaded after the update (if all went well).
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 |
# File 'lib/active_directory/base.rb', line 378 def update_attributes(attributes_to_update) return true if attributes_to_update.empty? operations = [] attributes_to_update.each do |attribute, values| if values.nil? || values.empty? operations << [ :delete, attribute, nil ] else values = [values] unless values.is_a? Array values = values.collect { |v| v.to_s } current_value = begin @entry[attribute] rescue NoMethodError nil end operations << [ (current_value.nil? ? :add : :replace), attribute, values ] end end @@ldap.modify( :dn => distinguishedName, :operations => operations ) && reload end |
#valid_attribute?(name) ⇒ Boolean
534 535 536 |
# File 'lib/active_directory/base.rb', line 534 def valid_attribute? name @attributes.has_key?(name) || @entry.attribute_names.include?(name) end |