Umer
Umer

Reputation: 43

check_password() in django always returning false

I am making a custom reset password module. I am checking the old password with django auth User model. But check_password is always returning false. Please help if there is mistake in my logic.

views.py

def user_pass_change(request):
    pass_old = request.POST.get('old_pass')
    hash_pass_new = make_password(request.POST.get('new_pass'))
    username = request.POST.get('username')
    user = User.objects.get(username=username)
    if user:
        check = check_password(user.password,pass_old)
        
        if check:
            User.objects.filter(username=username).update(password=hash_pass_new)
            messages.success(request, 'Password changed !')
            return redirect('/login')
        else:
            messages.warning(request, 'Wrong old password')
            return redirect('/login')
    else:
        messages.warning(request, 'Invalid Username !')
        return redirect('/login')

I have tried including these hashers in setting.py

PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
    'django.contrib.auth.hashers.BCryptPasswordHasher',
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.Argon2PasswordHasher',
]

Thanks in advance

Upvotes: 1

Views: 2286

Answers (1)

Swetank Poddar
Swetank Poddar

Reputation: 1291

user.password is a HASH of the password and not the actual password. check_password expects a raw string. [Django Docs]

To check if the current password is same as the pass_old you can do this:

check = user.check_password(pass_old) # user is the User object

Upvotes: 2

Related Questions