Flask 更新密码后无法登录

问题描述 投票:0回答:1

我尝试创建一种在 Flask 中更新用户密码的方法,但由于某种我不知道的原因,更新后用户无法再次登录。它说密码不正确,我看不出可能出了什么问题,任何帮助将不胜感激

在我的路线下方,我使用 bcrypt 对密码进行哈希处理。我也尝试将其解码为 utf8 但没有帮助:

@app.route('/change-password', methods=['GET', 'POST'])
@login_required
def change_password():
    if request.method == 'POST':
        current_password = request.form.get('current_password')
        new_password = request.form.get('new_password')
        confirm_password = request.form.get('confirm_password')

        if new_password != confirm_password:
            flash('As novas senhas não coincidem.')
            return redirect(url_for('change_password'))

        user_password_hash = get_user_password_hash(current_user.id)

        if not bcrypt.check_password_hash(user_password_hash, current_password):
            flash('Senha atual incorreta.')
            return redirect(url_for('change_password'))

        hashed_password = bcrypt.generate_password_hash(new_password)
        update_user_password(current_user.id, hashed_password)
        flash('Senha atualizada com sucesso.')
        return redirect(url_for('index'))

    return render_template('home/change_password.html')

def get_user_password_hash(user_id):
    user = User.query.get(user_id)
    return user.pwd

def update_user_password(user_id, new_password):
    user = User.query.get(user_id)
    if user:
        user.pwd = bcrypt.generate_password_hash(new_password)
        db.session.commit()

这是change_password.html:

<!DOCTYPE html>
<html>
<head>
    <title>Troca de Senha</title>
</head>
<body>
    <h1>Troca de Senha</h1>
    {% for message in get_flashed_messages() %}
        <p>{{ message }}</p>
    {% endfor %}
    <form method="POST" action="{{ url_for('change_password') }}">
        <label for="current_password">Senha Atual:</label>
        <input type="password" id="current_password" name="current_password" required><br><br>

        <label for="new_password">Nova Senha:</label>
        <input type="password" id="new_password" name="new_password" required><br><br>

        <label for="confirm_password">Confirme a Nova Senha:</label>
        <input type="password" id="confirm_password" name="confirm_password" required><br><br>

        <input type="submit" value="Trocar Senha">
    </form>
</body>
</html>
python flask flask-sqlalchemy
1个回答
0
投票

您正在对密码进行双重哈希处理。

这个功能:

def update_user_password(user_id, new_password):
    user = User.query.get(user_id)
    if user:
        user.pwd = bcrypt.generate_password_hash(new_password)
        db.session.commit()

new_password
作为参数。这应该是用户输入的明文。但这不是你要传递的:

hashed_password = bcrypt.generate_password_hash(new_password)
update_user_password(current_user.id, hashed_password)

您已经对它进行了哈希处理,然后将哈希值传递给再次对其进行哈希处理的函数。

© www.soinside.com 2019 - 2024. All rights reserved.