以下は、職場で ActiveDirectory サーバーからのユーザー ログインを確認するためにnet-ldap gemで使用するサンプル コードです。
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
最後のfirst.displayName.first
コードは少しばかげているように見えるため、いくつかの説明が役立つ場合があります。
Net::LDAP#search
一致するエントリが 1 つしかない場合でも、常に結果の配列を返します。への最初の呼び出しfirst
は、電子メール アドレスに一致した最初の (おそらく唯一の) エントリを見つけます。
検索によって返されたNet::LDAP::Entry
は、メソッド名を介して属性にアクセスできるのでsome_entry.displayName
、 と同じsome_entry['displayName']
です。
a のすべての属性は、Net::LDAP::Entry
値が 1 つしかない場合でも、常に値の配列です。複数の「displayName」値を持つユーザーを持つのはばかげているかもしれませんが、LDAP の一般的な性質はそれが可能であることを意味します。最後のfirst
呼び出しでは、1 つの文字列の配列がユーザーのフル ネームの文字列に変わります。