Understanding Django-LDAP authentication Understanding Django-LDAP authentication python python

Understanding Django-LDAP authentication


This page might have what you are looking for: https://pypi.python.org/pypi/django-auth-ldap concerning the LDAP backend. You are lucky that one exists, so you don't have to code an auth backend yourself :-)

Basically django.contrib.auth.models already has a User object that contains everything you need about the user. So you don't need to create a new models.py.

You just need to authenticate yourself in your views.py, in a login function, using

from django.contrib.auth import authenticate, loginuser = authenticate(username=request.REQUEST.get('email'), password=request.REQUEST.get('password'))# handle error cases, inactive users, ...login(request, user)

If user is None, then authentication failed. If not, you can explore this object to see what has the backend pulled for you.

Then, you can elect to create another model with User as a foreignKey if you want to keep Preferences linked to this User for this application but nor part of the LDAP.

In this case, you will need:

Models.py

The definition of the data that is important to you based on your application. You are going to pull the user data from the LDAP, and fill up this model with it and other preferences linked to the User:

from django.contrib.auth.models import User    class Profile(models.Model):    """User profile.  Contains some basic configurable settings"""    user = models.ForeignKey(User, unique=True)    phone_number = models.CharField(max_length=256, blank=True, default='')    ...

Views.py

  • in the login function, if request.method == 'POST', then get_or_create the user profile using the user your just got from authenticate.

    profile, profile_is_new = Profile.objects.get_or_create(user=user)


The django-auth-ldap docs are indeed written for developers who are familiar with Django. Also LDAP. If you're starting from scratch, I would recommend taking it one step at a time:

  1. The Django tutorial
  2. Django authentication
  3. Some kind of LDAP tutorial, if you're not already familiar.
  4. django-auth-ldap