![](/img/trans.png)
[英]Setting Refresh Token Signing Key to User's Hashed Password Using Flask_jwt_extended
[英]Changing user's password using Flask and SQLite
我正在嘗試實現一個 function 來更改用戶的密碼。 我只在數據庫中存儲 hash 而不是密碼,我想要求用戶先輸入舊密碼,然后再輸入新密碼。 我想檢查舊密碼的 hash 是否與存儲在數據庫中的密碼匹配,如果是,則使用新密碼對其進行更新。 我做錯了,因為代碼未通過驗證檢查,並且出現錯誤:“密碼無效”。 任何幫助,將不勝感激。
@app.route("/change_password", methods=["GET", "POST"])
@login_required
def change_password():
user_id=session["user_id"]
if request.method=="POST":
password = request.form.get("password")
hash = generate_password_hash(password)
new_password = request.form.get("new_password")
confirm_new_password = request.form.get("confirm_new_password")
new_hash = generate_password_hash(new_password)
#Validations:
if not password:
return apology("must provide password", 400)
if not new_password:
return apology("must provide a new password", 400)
#Ensure password confirmation is provided
if not confirm_new_password:
return apology("must confirm new password", 400)
#Check if new password matches
if new_password!= confirm_new_password:
return apology("password does not match", 400)
# Query database for the current password
rows = db.execute("SELECT * FROM users WHERE hash = ?", hash)
# Ensure username exists and password is correct
if len(rows) != 1:
return apology("invalid password", 400)
#Update DB with the new_hash
else:
db.execute ("UPDATE users SET hash=:new_hash WHERE id=:id", new_hash = new_hash, id = user_id)
return redirect("/")
else:
return render_template("change_password.html")
你的代碼有很多問題......
最大的問題
rows = db.execute("SELECT * FROM users WHERE hash = ?", hash)
您必須搜索用戶名,而不是 hash,,, Imagine。 兩個用戶有相同的密碼。 或者用戶輸入了錯誤的密碼。 但那是另一個用戶的密碼...
I never used direct access to sqlite, only via sqlalchemy, but from a quick look at the docs ( https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.executemany ) db.execute
does not返回例如行,但您需要查詢它。
例如,在您的db.execute
之后,您需要執行db.fetchone
或db.fetchall
,請參閱上面的鏈接文檔。
此外,可以改進代碼的順序。
例如,首先,您生成新密碼的 hash,然后檢查是否有密碼 - 這應該切換。
說到驗證,大部分都可以通過例如flask-wtforms 來完成,因此您自己不需要那么多驗證代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.