Here is sample code I use with the net-ldap gem to verify user logins from the ActiveDirectory server at my work:
require 'net/ldap' # gem install net-ldap
def name_for_login( email, password )
email = email[/\A\w+/].downcase # Throw out the domain, if it was there
email << "@mycompany.com" # I only check people in my company
ldap = Net::LDAP.new(
host: 'ldap.mycompany.com', # Thankfully this is a standard name
auth: { method: :simple, email: email, password:password }
)
if ldap.bind
# Yay, the login credentials were valid!
# Get the user's full name and return it
ldap.search(
base: "OU=Users,OU=Accounts,DC=mycompany,DC=com",
filter: Net::LDAP::Filter.eq( "mail", email ),
attributes: %w[ displayName ],
return_result:true
).first.displayName.first
end
end
The first.displayName.first code at the end looks a little goofy, and so might benefit from some explanation:
-
Net::LDAP#searchalways returns an array of results, even if you end up matching only one entry. The first call tofirstfinds the first (and presumably only) entry that matched the email address. -
The
Net::LDAP::Entryreturned by the search conveniently lets you access attributes via method name, sosome_entry.displayNameis the same assome_entry['displayName']. -
Every attribute in a
Net::LDAP::Entryis always an array of values, even when only one value is present. Although it might be silly to have a user with multiple “displayName” values, LDAP’s generic nature means that it’s possible. The finalfirstinvocation turns the array-of-one-string into just the string for the user’s full name.