django-ldap-auth user profile in django > 1.7

允我心安 提交于 2021-01-27 18:31:47

问题


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..


回答1:


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)


来源:https://stackoverflow.com/questions/40208862/django-ldap-auth-user-profile-in-django-1-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!