Skip to content

Instantly share code, notes, and snippets.

@teki
Created August 11, 2008 23:28
Show Gist options
  • Save teki/4967 to your computer and use it in GitHub Desktop.
Save teki/4967 to your computer and use it in GitHub Desktop.
reviewboard midified LDAP backend
class LDAPBackend:
"""
Authenticate against a user on an LDAP server.
"""
def authenticate(self, username, password):
try:
import ldap
ldapo = ldap.initialize(settings.LDAP_URI)
ldapo.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
if settings.LDAP_TLS:
ldapo.start_tls_s()
# resolve username
ldapo.simple_bind_s(settings.LDAP_ANON_BIND_UID, settings.LDAP_ANON_BIND_PASSWD)
res = ldapo.search_s(settings.LDAP_UID_DN, ldap.SCOPE_SUBTREE, settings.LDAP_FILTER_MASK % username)
if len(res) == 0:
raise ldap.NO_SUCH_OBJECT
ldapuser = res[0][0]
username = res[0][1]['uid'][0]
ldapo.simple_bind_s(ldapuser, password)
return self.get_or_create_user(username, ldapuser)
except ImportError:
pass
except ldap.INVALID_CREDENTIALS:
pass
except ldap.NO_SUCH_OBJECT:
pass
def get_or_create_user(self, username, ldapuser):
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
try:
import ldap
ldapo = ldap.initialize(settings.LDAP_URI)
ldapo.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
if settings.LDAP_TLS:
ldapo.start_tls_s()
ldapo.simple_bind_s(settings.LDAP_ANON_BIND_UID, settings.LDAP_ANON_BIND_PASSWD)
passwd = ldapo.search_s(ldapuser, ldap.SCOPE_SUBTREE)
if len(passwd) == 0:
raise ldap.NO_SUCH_OBJECT
first_name = passwd[0][1]['givenName'][0]
last_name = passwd[0][1]['sn'][0]
email = passwd[0][1]['mail'][0]
user = User(username=username,
password='',
first_name=first_name,
last_name=last_name,
email=email)
user.is_staff = False
user.is_superuser = False
user.save()
except ImportError:
pass
except ldap.INVALID_CREDENTIALS:
# FIXME I'd really like to warn the user that their
# ANON_BIND_UID and ANON_BIND_PASSWD are wrong, but I don't
# know how
pass
except ldap.NO_SUCH_OBJECT:
pass
except ldap.LDAPError:
pass
return user
def get_user(self, user_id):
return get_object_or_none(User, pk=user_id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment