Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django User.check_password wouldn't pass password check

Trying to write a unittest which should check whether user has inputted correct password.

Using Django's native auth function user.check_password for this.

The problem is that check_password woudn't accept user object's own password for some reason. For example, this raises an error:

assert user.check_password(user.password), "Password doesn't match"

user.password returns MD5 unicode string.

Does anyone know why doesn't this pass the check and how the check can be passed?

like image 987
0leg Avatar asked Jun 15 '15 15:06

0leg


1 Answers

This is happening because check_password accepts a raw string and you are passing a hash to it.

assert user.check_password(user.password)  # False because passing hash

assert user.check_password('my_password')  # True because accepts a raw string

user.password is a hash of, and metadata about, the password.

According to docs,

check_password(raw_password)
Returns True if the given raw string is the correct password for the user. (This takes care of the password hashing in making the comparison.)

So, just pass the actual raw string password to user.check_password() and the unittest will pass.

like image 137
Rahul Gupta Avatar answered Oct 04 '22 21:10

Rahul Gupta