Benji Benji - 1 year ago 93
Python Question

Querying SQLAlchemy User model by password never matches user

I want users in my Flask app to be able to change their email by providing a new email and their current password. However, when I try to look up the user by the password they entered with

, it never finds the user. How can I query the user so I can change the email while verifying the password?

@app.route('/changeemail', methods=['GET', 'POST'])
def change_email():
form = ChangeEmailForm(request.form)

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

if user and bcrypt.check_password_hash(user.password, =
return redirect(url_for("user.confirmed"))

return render_template('user/changeemail.html',form=form)

class ChangeEmailForm(Form):
email = TextField('email', validators=[DataRequired()])
password = PasswordField('password', validators=[DataRequired()])

class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String, unique=True, nullable=False)
password = db.Column(db.String, nullable=False)

Answer Source

The whole point of storing the hashed password is so that you never store the raw password. Query for the user that you're editing, then verify the password.

@app.route('/<int:id>/change-email', methods=['GET', 'POST'])
def change_email(id):
    user = User.query.get_or_404(id)

    if user.check_password(
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download