import ldap from django.contrib.auth.models import User from django.core.validators import email_re AUTH_LDAP_SERVER = 'xxx.xxx.xxx.xxx' class Authenticate: def authenticate(self, username=None, password=None): try: user = User.objects.get(email=username) if user.check_password(password): return user else: try: l = ldap.open(AUTH_LDAP_SERVER) except ldap.LDAPError, e: return None try: # Attempt to bind to the user's DN l.simple_bind_s(username, password) try: user = User.objects.get(email__exact=username) except: return None # Success. return user except ldap.INVALID_CREDENTIALS: return None except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None