2

I'm trying to set up LDAP authentication with my Django app using Django-Auth

The basic idea I want to do is any LDAP user with "IT - Help Desk" in the description would get mapped to a certain Django group, a user with "Admin" in the description would go to another Django group, and anyone else wouldn't be allowed in.

(There are legacy reasons I have to use the description field, so that's not an option to change)

Update: Some parts of the follow up conversation moved over here.

Greg_the_Ant
  • 489
  • 7
  • 26

1 Answers1

6

django-auth-ldap 1.0.9 (released 3/27) added a pair of Django signals that clients can use to do some custom population of user and profile objects. I would recommend connecting to the populate_user signal and using the LDAP attributes to update the user's group membership. e.g.:

import django_auth_ldap.backend

def update_groups(sender, user=None, ldap_user=None, **kwargs):
    # Remember that every attribute maps to a list of values
    descriptions = ldap_user.attrs.get("description", [])

    if "IT - Help Desk" in descriptions:
        # Add user to group
    else:
        # Remove user from group

django_auth_ldap.backend.populate_user.connect(update_groups)

This is even safe to combine with AUTH_LDAP_MIRROR_GROUPS, as the signal is sent after all built-in user population is complete.

psagers
  • 198
  • 4
  • Thanks! So where you have the comments e.g., "# Add user to gorup", what do I actually put there to add the user? Am I updating the auth_user table directly there? Or is it something I return? – Greg_the_Ant Mar 29 '11 at 10:51
  • Also Where would I place the code you mention? I tried putting it in settings.py but I get this error: ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined. – Greg_the_Ant Mar 29 '11 at 12:47
  • models.py is often a good place to put this sort of thing. The return value is ignored, so you should update the user object as you normally would. The Django documentation can tell you how to [manipulate a user's group membership](http://docs.djangoproject.com/en/1.3/topics/auth/#methods) – psagers Mar 29 '11 at 19:01