Skip to content

Instantly share code, notes, and snippets.

@peterbe
Created July 29, 2011 10:49
Show Gist options
  • Save peterbe/1113601 to your computer and use it in GitHub Desktop.
Save peterbe/1113601 to your computer and use it in GitHub Desktop.
ldap_lookup.py
import ldap
from django.conf import settings
from django.core.cache import cache
from django_auth_ldap.config import LDAPSearch
def fetch_user_details(email, force_refresh=False):
cache_key = 'ldap_user_details_%s' % hash(email)
if not force_refresh:
results = cache.get(cache_key)
if results:
print "LDAP cache hit"
return results
print "LDAP cache miss"
connection = ldap.initialize(settings.AUTH_LDAP_SERVER_URI)
connection.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
connection.simple_bind_s(settings.AUTH_LDAP_BIND_DN,
settings.AUTH_LDAP_BIND_PASSWORD)
dn = "mail=%s,o=com,dc=mozilla" % email
search = LDAPSearch(dn, ldap.SCOPE_BASE)
results = search.execute(connection)
if results:
cache.set(cache_key, results[0][1], 60 * 60)
return results[0][1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment