Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect a changed password in Django

When a user changes their password, I want to send a signal so that I can do some stuff on some models.

How can I create this signal?

I've looked at the post_save signal for User:

post_save.connect(user_updated, sender=User)

However, there doesn't seem to be anything in there for me to check if the password was changed:

def user_updated(sender, **kwargs):
    print(kwargs) # {'created': False, 'raw': False, 'instance': <User: 100002>, 'update_fields': None, 'signal': <django.db.models.signals.ModelSignal object at 0x7ff8862f03c8>, 'using': 'default'}

I also see that there is a password_change_done auth view, but I'm not sure how I'd use it. https://docs.djangoproject.com/en/1.10/topics/auth/default/#built-in-auth-views

Any ideas?

like image 911
43Tesseracts Avatar asked Jan 01 '17 04:01

43Tesseracts


People also ask

How can I see my password in Django?

In order to use the built-in Django check_password() function, we need to import it, which is shown in the first line of code. So the current password of the user is, request. user. password, which we store in the currentpassword variable.

Is there a password field in Django?

Django provides a flexible password storage system and uses PBKDF2 by default. Those are the components used for storing a User's password, separated by the dollar-sign character and consist of: the hashing algorithm, the number of algorithm iterations (work factor), the random salt, and the resulting password hash.

Can we decrypt Django password?

@anotheruser Yes, you can't 'decrypt' a hashed password through django. (A hash is a one-way function not really encryption). You could possibly save the password of the user in plaintext in the DB, when they create a user account. See: stackoverflow.com/questions/44109/…

Where are Django passwords stored?

In the common case of using Django's cache session store, the users' password are stored in clear text in whatever cache storage you have configured (typically Memcached or Redis).


1 Answers

You could use a pre_save signal. kwargs['instance'] will contain the updated password and you can get the old password with User.objects.get(id= user.id).password

@receiver(pre_save, sender=User)
def user_updated(sender, **kwargs):
    user = kwargs.get('instance', None)
    if user:
        new_password = user.password
        try:
            old_password = User.objects.get(pk=user.pk).password
        except User.DoesNotExist:
            old_password = None
        if new_password != old_password:
        # do what you need here
like image 112
Messaoud Zahi Avatar answered Sep 30 '22 16:09

Messaoud Zahi