1

Im using the ruby net/ldap gem to query against my AD server to get if a user is the member of a group or not and for the life of me cannot figure out where I am going wrong. This is my code (I referenced this answer to come up with the filter - https://stackoverflow.com/a/9890107/1664675):

  def query(username)
    result  = nil
    ldap    = Net::LDAP.new(@ldap_settings)   #ldap_settings has the authentication stuff
    filter = "(&(objectClass=user)(sAMAccountName=#{username})(memberof=CN=group-name,OU=Linux Groups,OU=Linux))"
    if ldap.bind
      ldap.search(:base => @base, :filter => filter) do |object|
        puts object.memberof
        end
    else
      raise 'Authentication Error!'
    end
    result
  end

When I call this function as puts Classname.new.query(username) it returns nothing.

When I user the filter filter = "(&(objectClass=user)(sAMAccountName=#{username}))" , I can list all the groups the user is part of. Is there any way to just check if the user is part of a group ?

letsc
  • 2,515
  • 5
  • 35
  • 54

2 Answers2

1

Your query is correct, my suggestion is use the count() method to return the information you want.

If count() > 0 then
#is part of group
else
#is not part of group
End if

regards

Daniel PC
  • 46
  • 4
0

This is what I ended up doing:

def query(username)
    result  = nil
    ldap    = Net::LDAP.new(@ldap_settings)   #ldap_settings has the authentication stuff
    filter = "(&(objectClass=user)(sAMAccountName=#{username}))"
    if ldap.bind
      ldap.search(:base => @base, :filter => filter) do |object|
        puts object.memberof.include?("CN=group-im-looking-for,OU=myou,OU=ou,DC=dc,DC=dc,DC=dc")
        end
    else
      raise 'Authentication Error!'
    end
    result
  end

This returns True if user is part of the group else False.

letsc
  • 2,515
  • 5
  • 35
  • 54