Skip to content

Instantly share code, notes, and snippets.

@chrisa
Created April 1, 2009 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisa/88728 to your computer and use it in GitHub Desktop.
Save chrisa/88728 to your computer and use it in GitHub Desktop.
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