Search code examples
pythonflask-sqlalchemyflask-loginflask-security

Flask Security updating password not working


I am trying to use flask-Security to change the password. Basically, there are no errors being thrown but the hash in my database is not updating. When creating the initial password, everything works fine.

However, when I try to update using the code in update.py the password isn't updating. I appreciate your insight. Thank you.

update.py

buyer = Buyers.query.filter_by(id=buyer_id).first()
                    buyer.password = generate_password_hash(form.password.data)
                    db.session.commit()
                    flash('Password has been updated')

models.py

class Buyers(db.Model, UserMixin):
    __tablename__ = 'buyers'

    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(64), unique=True, index=True, nullable=False)
    firstname = db.Column(db.String(64), index=True, nullable=False)
    lastname = db.Column(db.String(64), index=True, nullable=False)
    company = db.Column(db.Integer, db.ForeignKey('company.id'))
    password_hash = db.Column(db.String(128))

    def __init__(
        self, email, firstname, lastname, company, password
    ):
        self.email = email
        self.firstname = firstname
        self.lastname = lastname
        self.company = company
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

Solution

  • Not totally sure what you are trying to accomplish - but the code snippets have your User model with a field password_hash - not password. Flask-Security requires certain defined model names to work. Not sure where you are getting check_password_hash() and generate_password_hash()....

    The way Flask-Security updates password is:

    user.password = hash_password(password)
    _datastore.put(user)
    _datastore.commit()
    

    Oh - and I assume you are Flask-Security-Too (which is a maintained fork).....