dld
dld

Reputation: 43

Flask bcrypt.check_password_hash() always returns False, can't narrow in on my mistake

While trying to write a login functionality in flask, I wanted to try 'bcrypt' flask extensio. When I use_bcrypt.check_password_hash()_ method to compare user form input password against that users saved password in the db, it always returns false.

Here is the code I use to generate passwords:

    hashPwd = bcrypt.generate_password_hash('form.password.data')

Here is the code I use to check the candidate password against the saved one:

if form.validate_on_submit():
    user = User.query.filter_by(username=form.username.data).first()

    if user and bcrypt.check_password_hash(user.password, form.password.data):
        login_user(user, remember=form.rememberMe.data)

If I do User.query.get(1).password in python shell, the password is in format:

u'$2b$12$JOXUftWBbn/egABOkAYNwezGKfh6GzIHOofUnvx73AiSOfoNWEGFC'

When I run the same query in code, the password is:

$2b$12$JOXUftWBbn/egABOkAYNwezGKfh6GzIHOofUnvx73AiSOfoNWEGFC

The u' in the first pw is the only difference and that might be the issue cause, but I dont know what it is.

Any ideas?

Upvotes: 3

Views: 8293

Answers (2)

Carlos Ramires
Carlos Ramires

Reputation: 1

The problem is the quotation marks in ('form.password.data')

write as hashPwd = bcrypt.generate_password_hash(form.password.data)

Upvotes: 0

Dmitri G
Dmitri G

Reputation: 41

From http://flask-bcrypt.readthedocs.io/en/latest/

pw_hash = bcrypt.generate_password_hash('hunter2')
bcrypt.check_password_hash(pw_hash, 'hunter2') # returns True

The reverse function needs to check the hash against the password, in your case user.password should actually be hashPwd

if user and bcrypt.check_password_hash(hashPwd, form.password.data):

Upvotes: 4

Related Questions