Search code examples
pythondjangodjango-auth-ldap

django-ldap-auth user profile in django > 1.7


I'm trying to implement django-ldap-auth in my project and everything seems to work just fine. The problem is, that package doesn't support user profile field population for Django versions newer than 1.7.

From docs:

Note Django 1.7 and later do not directly support user profiles. In these versions, LDAPBackend will ignore the profile-related settings.

I've added this to my settings.py but nothing happens(as expected):
AUTH_LDAP_PROFILE_ATTR_MAP = {"description": "description"}

My question is: How can I enable AUTH_LDAP_PROFILE_ATTR_MAP in newer django versions?

EDIT: I'm thinking of using custom user model but I'm not sure if that's the best way here..


Solution

  • I solved this using one-to-one User profile model and populate_user signal emitted by django-ldap-auth.

    Code

    from __future__ import unicode_literals
    import django_auth_ldap.backend
    from fences.models import Profile
    from django.db import models
    
    def populate_user_profile(sender, user=None, ldap_user=None, **kwargs):
      temp_profile = None
      bucket = {}
    
      try:
          temp_profile = user.profile
      except:
          temp_profile = Profile.objects.create(user=user)
    
      bucket['street_address'] = ldap_user.attrs.get('streetAddress')
      bucket['telephone_number'] = ldap_user.attrs.get('telephoneNumber')
      bucket['title'] = ldap_user.attrs.get('title')
    
      for key, value in bucket.items():
          if value:
              setattr(user.profile, key, value[0].encode('utf-8'))
      user.profile.save()
    
    django_auth_ldap.backend.populate_user.connect(populate_user_profile)