I have a simple App to authenticate a user login. I wrote a test password script to ensure the authentication is working. However, it never succeeds even though it should for my testcase.
Here is the code:
# Validate Form
if form.validate_on_submit():
email = form.email.data
password = form.password_hash.data
password_hash = generate_password_hash("password", "sha256")
# Clear the form
form.email.data = ''
form.password_hash.data = ''
# Lookup User Password by email
pw_to_check = get_user_pwd(email) # this gets the DB password (hashed)
# Check Hashed Password
passed = check_password_hash(pw_to_check, password)
return render_template("test_pw.html",
email = email,
password = password,
pw_to_check = pw_to_check,
password_hash =password_hash,
passed = passed,
form = form)
def get_user_pwd(email): # this function gets the user password by email
with connection:
with connection.cursor() as cursor:
password_hash = "NONE"
cursor.execute("SELECT password_hash FROM users WHERE email=email;")
password_hash = cursor.fetchone()[0]
return password_hash
HTML
{% if email %}
<h1>Email: {{ email }}</h1>
<h1>Password: {{ password }}</h1>
<br/>
<h2>I found this info:</h2>
<br/>
Email: {{email}}<br/>
PW in DB (hash): {{pw_to_check}}<br/>
PW in form (hash): {{password_hash}}<br/>
<br/>
Passed: {{ passed }}
{% else %}
<h1>What's Your Email and Password?</h1>
<br/>
<form method="POST">
{{ form.hidden_tag() }}
{{ form.email.label(class="form-label") }}
{{ form.email(class="form-control") }}
<br/>
{{ form.password_hash.label(class="form-label") }}
{{ form.password_hash(class="form-control") }}
<br/>
{{ form.submit(class="btn btn-secondary") }}
</form>
The results from the "passed = check_password_hash(pw_to_check, password)" statement is always false. Is there something I am missing? It seems very simple but I am sure I got something wrong. ANy help will be much appreciated. [email protected]
A few things:
1 - I made sure that the password hash stored in the DB was generated using the generate_password_hash("password", "sha256") (password=password12345 )and
2 - The password used in the login form is exactly the same (password12345)
3 - There was a similar question posted and the problem there was that the password_hash being sent to the check_password_hash function was a tupple. SO the solution was to point ot he first element of the tupple[0]. In my case, I am using password_hash = cursor.fetchone()[0] to avoid that problem.
pw_to_checkandpasswordright before yourcheck_password_hash(...)call.