Created
February 15, 2019 07:14
-
-
Save bpereto/e3f0dd60f098ea0d9dd2d8c130f737c3 to your computer and use it in GitHub Desktop.
RemoteUserLdapBackend: Combine the RemoteUser Authentication and the django-auth-ldap to populate Users in Django
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Combine the RemoteUser Authentication and the django-auth-ldap | |
to populate Users in Django | |
https://docs.djangoproject.com/en/2.1/howto/auth-remote-user/ | |
https://django-auth-ldap.readthedocs.io/en/latest/ | |
""" | |
import logging | |
from django.contrib.auth import load_backend, login | |
from django.contrib.auth.backends import RemoteUserBackend | |
logging.getLogger('RemoteUserLdapBackend') | |
class RemoteUserLdapBackend(RemoteUserBackend): | |
""" | |
Take the REMOTE_USER from the RemoteUserMiddleware and populate | |
user, attributes and groups with the LDAPBackend from django_auth_ldap. | |
""" | |
def authenticate(self, request, remote_user=None): | |
""" | |
load LDAPBackend and authenticate the user against the LDAPBackend. | |
""" | |
logging.info('Trying to authenticate %s', remote_user) | |
backend = load_backend('django_auth_ldap.backend.LDAPBackend') | |
user = backend.populate_user(remote_user) | |
if user is not None: | |
# If everything went well we should have a user to login | |
logging.debug('Found %s and populate it with LDAP Backend', user) | |
login(request, user, backend='django_auth_ldap.backend.LDAPBackend') | |
return user |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment