Created
April 1, 2009 15:04
-
-
Save chrisa/88728 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'java' | |
import javax.naming.InitialContext | |
import javax.naming.directory.SearchControls | |
import javax.naming.AuthenticationException | |
import javax.naming.CommunicationException | |
module Ldap | |
module JndiLdap | |
# make the SUBTREE_SCOPE constant available | |
SearchControls.field_reader(:SUBTREE_SCOPE) | |
class Result | |
def initialize(data) | |
@data = Hash.new | |
data.keys.each do |key| | |
@data[key] = [ data[key].gsub(/^#{key}: /, '') ] | |
end | |
@data['dn'] = @data['distinguishedName'].first | |
end | |
def [](key) | |
@data[key] | |
end | |
end | |
def ldap_search(config, string) | |
initCtx = InitialContext.new | |
ctx = initCtx.lookup(config[:jndi]) | |
ctls = SearchControls.new | |
ctls.setSearchScope(ctls.SUBTREE_SCOPE) | |
answer = ctx.search('', string, ctls) | |
while answer.hasMoreElements | |
element = answer.nextElement | |
attrs = element.getAttributes | |
result = Hash.new | |
attrs.getIDs.each do |id| | |
result[id] = attrs.get(id).toString | |
end | |
yield Result.new(result) | |
end | |
answer.close | |
ctx.close | |
end | |
def ldap_bind(config, user, pass) | |
initCtx = InitialContext.new | |
ctx = initCtx.lookup(config[:jndi]) | |
bindCtx = ctx.lookup('') | |
bindCtx.addToEnvironment('java.naming.security.principal', user) | |
bindCtx.addToEnvironment('java.naming.security.credentials', pass) | |
bindCtx.addToEnvironment('com.sun.jndi.ldap.connect.pool', 'false') | |
begin | |
bindCtx.lookup('') | |
rescue AuthenticationException | |
raise Ldap::Exception.new("Invalid credentials") | |
ensure | |
ctx.close | |
bindCtx.close | |
end | |
end | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment