Django User.check_password wouldn't pass password check

6k views Asked by At

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?

1

There are 1 answers

0
Rahul Gupta On BEST ANSWER

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.