Skip to content

Instantly share code, notes, and snippets.

@seven1m
Created September 30, 2008 16:46
Show Gist options
  • Save seven1m/13875 to your computer and use it in GitHub Desktop.
Save seven1m/13875 to your computer and use it in GitHub Desktop.
net/ldap example code for Active Directory
require 'net/ldap'
# how to "bind" to your ldap/ad server...
LDAP_HOST = 'server'
LDAP_PORT = 389
LDAP_USERNAME = 'cn=Username;cn=Users;dc=domain;dc=com'
LDAP_PASSWORD = 'your user password'
LDAP_BASE = 'dc=domain;dc=com'
# replace "domain" and "com" above with your AD domain
class User < ActiveRecord::Base
def member_of?(group)
@@ldap ||= Net::LDAP.new(
:host => LDAP_HOST,
:port => LDAP_PORT,
:auth => {:method => :simple, :username => LDAP_USERNAME, :password => LDAP_PASSWORD}
)
@@ldap.search(
:base => LDAP_BASE,
:filter => Net::LDAP::Filter.eq('sAMAccountName', self.username),
:attributes => %w(memberOf)
).first.memberOf.include? "CN=#{group},OU=Groups,DC=domain,DC=com"
end
end
# this code allows us to test that a user is in a group
@user = User.find(1)
@user.member_of?('staff')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment