Reputation: 15824
It's impossible to get passwords of a user in any Django app, by design.
I'm implementing a change password
feature for my Django app, and one of the requirements is to ensure users don't keep a new password that's the same as their previous one.
I can't do string comparison here, so what's the optimal pattern to follow in this case?
Here's what I'm thinking: accessing my change password
feature requires re-auth (i.e. users have to input the pass again). I can conceivably save the password string in a session variable at this point (e.g. session.request['old_password']
), and then compare this session variable with the string of the new password the user sets? Any security concerns with this kind of a pattern?
Upvotes: 1
Views: 2123
Reputation: 43300
Following on from my suggestion under e4c5's answer, it would appear as though there are existing packages such as Django Password Validator that will do this for you so you don't really need to write it yourself.
Essentially, it seems that this works via storing the previously used hashed passwords in a database and then comparing the new hashed password to those currently stored.
See the source code for their validator for more information.
Upvotes: 3
Reputation: 53734
You don't need to store the old password in a session and you shouldn't either. Because the session data get's saved in the session storage and for that brief period when the password is being changed, it's there in plain text format. Theoretically an attacker could use a database event or trigger to capture these plain text password objects. The better approach would be to use django's built in password functions.
check_password(password, encoded) If you’d like to manually authenticate a user by comparing a plain-text password to the hashed password in the database, use the convenience function check_password(). It takes two arguments: the plain-text password to check, and the full value of a user’s password field in the database to check against, and returns True if they match, False otherwise.
In your case you would need to create a custom form, that calls this method as part of it's clean() method. If the above function call returns true, you need to raise a validation error saying the old password is being reused.
Upvotes: 5