Mr. lindroid
Mr. lindroid

Reputation: 181

Flask Bcrypt password hash doesn’t match, How to solve it?

I am trying to make a simple web app using Flask. And I tried to run it with sqlite. And it works perfectly. The only problem is when I tried to host the app on a Shared hosting server,with MySQL as the database, I've faced some password matching issues. When I lookup at the problem, I saw flask-bcrypt password hashes aren’t matching. And I Don't know how to fix it. Here is the code :

from flask_bcrypt import Bcrypt

app.config["SECRET_KEY"] = "super-secret-key"
cryptor = Bcrypt(app)

Hashing and storing in database:

Note: I've tried to match passwords using the Terminal & Interpreter before storing on database. And it matched, But once stored and pulled back it doesn’t match.
password = cryptor.generate_password_hash(request.form.get("password")).decode("utf-8")

user_obj = Users(password=password)
db.session.add(user_obj)
db.session.commit()

Matching:

data = Users.query.filter_by(email=form.username.data).first()
if cryptor.check_password_hash(data.password, form.password.data):
    #pass the login check
else:
    #dont pass

Sqlalchemy model:

class Users(db.model):
    password = db.Column(db.String(50), nullable=False)

Upvotes: 1

Views: 1417

Answers (1)

unga
unga

Reputation: 80

Try changing this:

class Users(db.model):
    password = db.Column(db.String(50), nullable=False)

to this:

class Users(db.model):
    password = db.Column(db.String(X), nullable=False)

(X = the length of the hashed password)

When you specify 50 you are telling the database to reserve a space for 50 characters, which cuts off most of the hashed password when you store it. Increasing the space reserved will allow you to verify the hash. Refer to Flask SQLAlchemy Docs.

The reason why you did not have any problems with Sqlite is because its optional to specify the maximum length of the string. (Same goes for PostgreSQL)

Upvotes: 3

Related Questions