importldapfromdjango.contrib.auth.modelsimportUserfromdjango.core.validatorsimportemail_reAUTH_LDAP_SERVER='xxx.xxx.xxx.xxx'classAuthenticate:defauthenticate(self,username=None,password=None):try:user=User.objects.get(email=username)ifuser.check_password(password):returnuserelse:try:l=ldap.open(AUTH_LDAP_SERVER)exceptldap.LDAPError,e:returnNonetry:# Attempt to bind to the user's DNl.simple_bind_s(username,password)try:user=User.objects.get(email__exact=username)except:returnNone# Success.returnuserexceptldap.INVALID_CREDENTIALS:returnNoneexceptUser.DoesNotExist:returnNonedefget_user(self,user_id):try:returnUser.objects.get(pk=user_id)exceptUser.DoesNotExist:returnNone