Skip to content

Instantly share code, notes, and snippets.

@zodman
Created October 4, 2010 22:05
Show Gist options
  • Save zodman/610541 to your computer and use it in GitHub Desktop.
Save zodman/610541 to your computer and use it in GitHub Desktop.
from django.contrib.auth.backends import RemoteUserBackend, ModelBackend
from django.contrib.auth.models import User
from mosketeros.settings import LDAP_SERVER,LDAP_BIND,LDAP_SEARCH
import ldap
class DjangoAuth(ModelBackend):
create_unknown_user = False
supports_anonymous_user = False
class LdapUserAuth(DjangoAuth):
def check_ldap(self, username):
ldap_client = ldap.open(LDAP_SERVER)
ldap_user,ldap_pass = LDAP_BIND
ldap_client.simple_bind(ldap_user,ldap_pass)
self._result(ldap_client)
str_search, user_to_search = LDAP_SEARCH
ldap_client.search(str_search ,ldap.SCOPE_SUBTREE,user_to_search % username)
id,res = self._result(ldap_client)
if len(res) > 0:
# Pertenece a ldap
return True
else:
return False
def auth_ldap(self,username,password):
ldap_client = ldap.open(LDAP_SERVER)
ldap_client.simple_bind(username,password)
try:
ldap_client.result()
return True
except ldap.INVALID_CREDENTIALS:
return False
def _result(self, ldap_client):
try:
return ldap_client.result()
except ldap.INVALID_CREDENTIALS as e:
assert False, e
def authenticate(self, username, password ):
#success = self.check_ldap(username)
success = self.auth_ldap(username,password)
if not success:
return None
else:
try:
user = User.objects.get(username = username)
return user
except User.DoesNotExist:
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment