0

We recently switched from one LDAP system to another. Unfortunately, not only the LDAP server changed but all usernames did too.

I managed to configure django_auth_ldap to deal with two LDAP servers, however I can not prevent the creation of new users in my database.

I tried to hook up a listener to django_auth_ldap.backend.populate_user.connect but that signal gets evaluated after a user had been created.

So what's the best approach to do:

  • authenticate user
  • check if username in database
  • check for alternative username in database
  • update username if necessary (old & new user mapping found)
  • create new user if not found anywhere

EDIT I'm aware of signal handlers, but I don't know how (and where in the code) to solve the task of preventing duplicate user creation. Where should I hook my code up that checks for old vs new usernames?

EDIT2:

I've tried to following, but still a new_name user is being created.

# touple of old user and new user names
username_list = [('old_name', 'new_name') ]

@receiver(pre_save, sender=User)
def check_if_user_exists(sender, **kwargs):
    try:
        print "check_if_user_exists:"
        user_instance = kwargs['instance']
        print user_instance
        if any([x[1] == user_instance.username for x in username_list]):
            print "new user name found!"
            # get old username
            user = User.objects.get(username = x[0])
            user.username = user_instance.username
            return user
        else:
            print "user not found :("
    except ObjectDoesNotExist:
        print ('user not found')
        pass
memyself
  • 11,907
  • 14
  • 61
  • 102
  • Would this link help: https://docs.djangoproject.com/en/dev/ref/signals/#django.db.models.signals.pre_save ? – Henrik Andersson Apr 15 '13 at 15:14
  • @limelights sure, but it doesn't help me, since it's just a link to signal docs. I need to some input regarding the implementation. – memyself Apr 15 '13 at 15:16

2 Answers2

0

This is how you implement a signal_handler on a pre_save. These should live in your models.py.

@receiver(pre_save, sender=MyModel)
def check_if_user_exists_based_on_whatever(sender, **kwargs):
    try:
        user = MyModel.objects.get(kwargs['instance'].<field_to_get_on_model>)
        user.username = "new_username"
        user.save()
    except ObjectDoesNotExist:
        user = MyModel.create(name="mymyself", lastname="andI")

This is just a basic example, I don't really know all of your validation logic. ^_^

Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
0

I ended up writing my own authentication backend, overwriting get_or_create_user.

memyself
  • 11,907
  • 14
  • 61
  • 102