Skip to content

Instantly share code, notes, and snippets.

@nikolaik
Created November 3, 2014 22:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nikolaik/05e0fe79493eb4ba4ac2 to your computer and use it in GitHub Desktop.
Save nikolaik/05e0fe79493eb4ba4ac2 to your computer and use it in GitHub Desktop.
django-auth-ldap email or username authentication
from django_auth_ldap.backend import LDAPBackend, _LDAPUser
class LDAPUsernameBackend(LDAPBackend):
settings_prefix = "AUTH_LDAP_U_"
class LDAPEmailBackend(LDAPBackend):
settings_prefix = "AUTH_LDAP_E_"
def get_or_create_user(self, email, ldap_user):
"""
Use the Posixuser uid field as username instead of form value (email).
This must return a (User, created) 2-tuple for the given LDAP user.
username is the Django-friendly username of the user. ldap_user.dn is
the user's DN and ldap_user.attrs contains all of their LDAP attributes.
"""
model = self.get_user_model()
username_field = getattr(model, 'USERNAME_FIELD', 'username')
kwargs = {
username_field + '__iexact': ldap_user.attrs['uid'][0],
'defaults': {
username_field: ldap_user.attrs['uid'][0].lower(),
'email': email
}
}
return model.objects.get_or_create(**kwargs)
# snipped from settings.py
AUTHENTICATION_BACKENDS = (
'app.backends.LDAPEmailBackend',
'app.backends.LDAPUsernameBackend',
'django.contrib.auth.backends.ModelBackend',
)
# LDAP username auth
AUTH_LDAP_U_USER_SEARCH = LDAPSearch("ou=people,dc=example,dc=com", ldap.SCOPE_ONELEVEL, "(uid=%(user)s)")
# User attribute mappings
AUTH_LDAP_U_USER_ATTR_MAP = {
"first_name": "givenName",
"last_name": "sn",
"email": "mail",
}
# Allways update the django user object on authentication.
AUTH_LDAP_U_ALWAYS_UPDATE_USER = True
# LDAP email auth
AUTH_LDAP_E_USER_SEARCH = LDAPSearch("ou=people,dc=example,dc=com", ldap.SCOPE_ONELEVEL, "(mail=%(user)s)")
AUTH_LDAP_E_USER_ATTR_MAP = AUTH_LDAP_U_USER_ATTR_MAP
AUTH_LDAP_E_ALWAYS_UPDATE_USER = AUTH_LDAP_U_ALWAYS_UPDATE_USER
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment