You didn't fetch the row here:
session["user_id"] = c.execute("SELECT username FROM users WHERE(:username=:username)", {"username": username})
c.execute()
returns the cursor object, you can't put that into a session variable. It should be
session["user_id"] = c.execute("SELECT username FROM users WHERE(:username=:username)", {"username": username}).fetchone()[0]
But there doesn't seem to be a reason to do another query here. It's just going to return the same username that's in the parameter. So just write
sesion["user_id"] = username
BTW, it's generally considered poor security design to distinguish invalid usernames from invalid passwords. Just do a single query with both the username and password. If it fails, report "Invalid username or password".
if (c.execute("SELECT COUNT(*) FROM users WHERE username=:username AND password=:password", {"username" : username, "password": pwd_hash}).fetchone()[0] == 0):
flash("invalid username or password", "error")
return redirect("/login")
Other issues:
- You're assigning variables from the
request.form
parameters before you check that they were actually filled in.
- If you only need one row, use
fetchone()
instead of fetchall()[0]
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…