Skip to content

Instantly share code, notes, and snippets.

@zodman
Created April 10, 2012 23:20
Show Gist options
  • Save zodman/2355545 to your computer and use it in GitHub Desktop.
Save zodman/2355545 to your computer and use it in GitHub Desktop.
django Backend con ldap
# -*- coding: utf-8 -*-
""" Metodos de Autentificacion """
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
class DjangoAuth(ModelBackend):
""" Autentificacion del framework """
#create_unknown_user = False
#supports_anonymous_user = False
pass
class BackendRemoteUser(RemoteUserBackend):
""" Autentificacion remota """
pass
class LdapUserAuth(DjangoAuth):
""" Autentificacion utilizando LDAP (Active Directory)"""
def check_ldap(self, username):
""" Checar si el usuario existe en ldap
@username str nombre de usuario para checar
"""
import ldap
ldap_client = ldap.initialize(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):
""" Autentificacion para ldap
@username str usuario de LDAP
@password str contraseña de LDAP
"""
import ldap
ldap_client = ldap.initialize(LDAP_SERVER)
try:
ldap_client.simple_bind(username,password)
except ldap.SERVER_DOWN:
return False
except UnicodeEncodeError:
return False
try:
ldap_client.result()
return True
except ldap.INVALID_CREDENTIALS:
return False
def _result(self, ldap_client):
""" Checar el resultado de autenficacion
@ldap_client obj cliente de ldap
"""
try:
return ldap_client.result()
except ldap.INVALID_CREDENTIALS :
return False
def authenticate(self, username, password ):
""" Metodo de autentificacion del backend
@username str usuario
@password str contraseña
"""
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