为什么check_password_hash函数返回false?使用Flask、SQLite3和Werkzeug



我正在尝试使用Flask、Werkzeug和SQLite创建一个基本的登录函数。用户可以注册,他们的密码哈希存储在SQLite数据库中,尽管当我尝试使用正确的密码登录时,check_password_hash返回false。

目前,我正在将用户提供的密码与存储在SQLite数据库中的相关哈希进行比较,该数据库是在用户注册时使用generate_password_hash创建的。我已经阅读了Werkzeug文档,但找不到任何解决方案。

也许这与generate_password_hash从不两次输出相同的哈希有关?尽管我认为check_password_hash能够解决这个问题?

这是代码:

@app.route("/register", methods=["GET", "POST"])
def register():
"""Register user"""
if request.method == "GET":
return render_template("register.html")
if request.method == "POST":
with sqlite3.connect("finance.db") as conn:
cur = conn.cursor() 
username = request.form.get("username")
password = request.form.get("password")
confirm_password = request.form.get("confirm-password")
hash_value = generate_password_hash(password)
cur.execute("SELECT * FROM users WHERE username=?", (username,))
valid_username = cur.fetchone()

# Check input and format: Username already taken? Username entered? Password entered? passwords match?
if valid_username:
return ("Username not available")
if not username:
return("Please enter a username")
elif not password:
return("Please enter a password")
elif not confirm_password:
return("Please confirm your password")
elif password != confirm_password:
return ("Passwords do not match")
else:
cur.execute("INSERT INTO users (username,hash) VALUES (?,?)", (username,hash_value))
return redirect("/")

@app.route("/login", methods=["GET", "POST"])
def login():
"""Log user in"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Ensure username was submitted
if not request.form.get("username"):
return apology("must provide username", 403)
# Ensure password was submitted
elif not request.form.get("password"):
return apology("must provide password", 403)
# User login
# Query database for username and hash
with sqlite3.connect("finance.db") as conn:
cur = conn.cursor()
username_field = request.form.get("username")
cur.execute("SELECT username FROM users WHERE username = ?", (username_field,))
username = cur.fetchall()
cur.execute("SELECT hash FROM users WHERE username = ?", (username_field,))
pwhash = cur.fetchone()
# Ensure username exists and password is correct           
if len(username) != 1 or not check_password_hash(pwhash, request.form.get("password")):
print(check_password_hash(pwhash, request.form.get("password")))
return apology("invalid username and/or password", 403)
return redirect("/")
# User reached route via GET (as by clicking a link or via redirect)
else:
return render_template("login.html")

提前感谢您的帮助。

啊哈!解决了。语法错误,pwhash`是一个元组,因为这是fetchone((返回的,所以它需要是check_password_hash(pwhash[0],request.form.get("password"(非常感谢您的支持。我没有想到要单独测试check_password_hash函数,这样做让我意识到我正在使用元组。干杯@JanL。祝你今天愉快。

如果您使用的是sql数据库或任何其他数据库,请检查指定的字符长度。哈希算法返回长字符串,当推送到数据库时,这些字符串有时会被截断,这可能会导致验证错误。因此,请将密码长度设置为一个相当大的字符长度,以避免出现错误。

最新更新