问题描述
我正在尝试使用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 (?,?)",hash_value))
return redirect("/")
@app.route("/login","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 = ?",))
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。祝你有美好的一天。