Reputation: 95
The aim of this code is to validate a password that is entered using the passwords and usernames stored in a database. The table contains username (nick
) and password, passwords are encrypted using db.crypt
.
My code at the moment consists of:
def check_login(db, username, password):
"""returns True if password matches stored"""
cursor = db.cursor()
pass1 = db.crypt(password)
cursor.execute("SELECT password FROM users WHERE nick=?", (username,))
passcheck = cursor.fetchone()
if passcheck == pass1:
return True
else:
return False
But i keep getting an assertion error when running a unit test:
line 29, in test_check_login
self.assertTrue(users.check_login(self.db, username, password), "Password check failed for username%s" % username)
AssertionError: False is not true : Password check failed for nick jake
When I use print to show what passcheck
is retrieving it prints the correct encrypted pass word but inside of ('')
tags (as a tuple, I believe). But when I print cursor.fetchone()
it says None
. I'm unsure what is going wrong here, I encrypted the password being sent into the function so it can be correctly matched to that of the password stored in the DB. I assume passcheck
would retrieve the password that corresponds to the user nick
, that is passed through the function.
Any and all help is much appreciated.
Upvotes: 2
Views: 2889
Reputation:
cursor.fetchone()
fetches a row as a tuple:
passcheck == ("hashed password", )
You must compare agains passcheck[0]
or unpack the tuple:
passcheck, = cursor.fetchone()
Edit: Let the database do the comparing:
cursor.execute("SELECT * FROM users WHERE username= ? and password= ?",
(username, pass1))
found = cursor.fetchone()
if found:
# user exists and password matches
else:
# user does not exist or password does not match
Upvotes: 3