Login Function Flask Issue

42 Views Asked by At

I've been having issues with my login function not grabbing stored login info to login. So, for instance Ill register on my app then when I try to login with the info I just made, and I go to use the login info it flashes my message I have set up but the password and email are correct. Any thoughts on getting to work?

@app.route("/login", methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    elif request.method == 'POST':
        email = request.form['email']
        password = request.form['password']
        users = Users.query.filter_by(email=email)
        if users.count() == 1:
            user = users.first()
            if check_pw_hash(password, user.pw_hash):
                session['user'] = user.email
                flash('welcome back, ' + user.email)
                return redirect("/")
        flash('bad username or password')
        return redirect("/login")

{% extends "base.html" %}
{% block content %}

<h2>Login</h2>
<form action="/login" method="post">
  <p><label>Email<input type="text" name="email"/></label></p>
  <p><label>Password<input type="password" name="password"/></label></p>
  <p><input type="submit" value="Login"/></p>
</form>

{% endblock %}
1

There are 1 best solutions below

0
0x00 On

Depending on how you defined your Users tables it is possible that there is more than 1 user with the same email, which will cause count() to not be 1. Make sure the email is defined as unique AND that it exists in your database.

class Users(Base):
    id: Mapped[int] = mapped_column(primary_key=True)
    email: Mapped[str] = mapped_column(unique=True)
    password: Mapped[str]

Another option, is that you didn't post the code for the function check_pw_hash(password, user.pw_hash). Werkzeug does provide an utility function to check password hash werkzeug.security.check_password_hash(pwhash, password), the first parameter pwhash is the hashed password stored in your database and the second parameter password is the plain text password from the input. It is possible that in your function you are mixing them up which fails the check for the password. You should be doing something like:

from werkzeug.security import check_password_hash

def login():
  if request.method == "POST"
    # stuff
    if check_password_hash(user.password, request.form.get("password")):
      # set session
      return redirect("/")
    else:
      flash('bad username or password')
  return render_template("login.html")