gpt4 book ai didi

python - flask-bcrypt - ValueError : Invalid salt

转载 作者:太空狗 更新时间:2023-10-29 20:32:27 32 4
gpt4 key购买 nike

我正在使用 Flask 和 flask-Bcrypt 完成一个简单的用户登录。但是,当尝试使用存储在我的数据库中的用户登录时,我不断收到此错误

ValueError: Invalid salt

模型.py

class User(db.Model):

__tablename__ = "users"

id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False)
email = db.Column(db.String, nullable=False)
password = db.Column(db.String, nullable=False)
posts = db.relationship("Post", backref="author", lazy="dynamic")

def __init__(self, name, email, password):
self.name = name
self.email = email
self.password = bcrypt.generate_password_hash(password)

def __repr__(self):
return '<User {}>'.format(self.name)

View .py

@app.route("/login", methods=["GET", "POST"])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter(User.name == form.username.data).first()
if user and bcrypt.check_password_hash(user.password, form.password.data):
flash("you were just logged in!")
login_user(user)
return redirect(url_for("home"))
else:
flash("bad username or password")
return render_template("login.html", form=form)

表单.py

class LoginForm(Form):
username = StringField('username', validators=[DataRequired()])
password = PasswordField('password', validators=[DataRequired()])

最佳答案

我的问题与@tomClark 描述的类似

我使用 Postgres 作为我的 DDBB 和他的驱动程序,或者 DDBB 系统,总是编码一个已经编码的字符串。第二个编码过程创建一个无效的散列,如下所示:

'\\x24326224313224483352757749766438764134333757365142464f4f4f464959664d66673575‌​467873754e466250716f3166375753696955556b2e36'

正确的散列看起来像这样:

$2b$12$Wh/sgyuhro5ofqy2.5znc.35AjHwTTZzabz.uUOya8ChDpdwvROnm

为了解决它,我先将哈希解码utf8,然后将其保存到DDBB。

示例代码:

def set_password(self, pw):
pwhash = bcrypt.hashpw(pw.encode('utf8'), bcrypt.gensalt())
self.password_hash = pwhash.decode('utf8') # decode the hash to prevent is encoded twice

关于python - flask-bcrypt - ValueError : Invalid salt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34548846/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com