Лучшее решение, которое мне удалось найти, - это модель со следующим:
require 'net/ldap'
class User < ActiveRecord::Base
def after_initialize
@config = YAML.load(ERB.new(File.read("#{Rails.root}/config/ldap.yml")).result)[Rails.env]
end
def ldap_auth(user, pass)
ldap = initialize_ldap_con
result = ldap.bind_as(
:base => @config['base_dn'],
:filter => "(#{@config['attributes']['id']}=#{user})",
:password => pass
)
if result
# fetch user DN
get_user_dn user
sync_ldap_with_db user
end
nil
end
private
def initialize_ldap_con
options = { :host => @config['host'],
:port => @config['port'],
:encryption => (@config['tls'] ? :simple_tls : nil),
:auth => {
:method => :simple,
:username => @config['ldap_user'],
:password => @config['ldap_password']
}
}
Net::LDAP.new options
end
def get_user_dn(user)
ldap = initialize_ldap_con
login_filter = Net::LDAP::Filter.eq @config['attributes']['id'], "#{user}"
object_filter = Net::LDAP::Filter.eq "objectClass", "*"
ldap.search :base => @config['base_dn'],
:filter => object_filter & login_filter,
:attributes => ['dn', @config['attributes']['first_name'], @config['attributes']['last_name'], @config['attributes']['mail']] do |entry|
logger.debug "DN: #{entry.dn}"
entry.each do |attr, values|
values.each do |value|
logger.debug "#{attr} = #{value}"
end
end
end
end
end