Home > Software engineering >  Flask / Werkzeug showing up instead of error message for user connection to db
Flask / Werkzeug showing up instead of error message for user connection to db

Time:11-30

I'm trying to get the "error_statement_wrong" variable to show up when a user is trying to connect to the db with invalid credentials, but instead I get the Werkzeug showing up and stating:

"mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'xxx'@'DESKTOP-xxxxx' (using password: YES)"

So i know the code is most probably OK but I cannot check if the error statement does appear as it should in the web front. How do I check this?

@app.route('/login', methods=["POST","GET"])
def login():
        if request.method == 'POST':

            user_name = request.form.get('user_name')
            pass_word = request.form.get('pass_word')

            mydb = mysql.connect(
                  host="127.0.0.1",              
                  user=user_name,
                  password=pass_word,
                  database = "test_db"
                )

            mycursor = mydb.cursor()
            sql = "select username, password from user where username=%s and password=%s"
            val = (user_name, pass_word)
            mycursor.execute(sql, val)
            result = mycursor.fetchone()
            if result:
                success_statement = "Successfully logged in"
                return render_template("index0.html", success_statement=success_statement)
            else:
                error_statement_wrong = "Wrong credentials"
                return render_template("login.html", error_statement_wrong=error_statement_wrong, user_name=user_name, pass_word=pass_word)

        else:
            return render_template("login.html")

CodePudding user response:

The issue is that mysql.connect is throwing an error (if you weren't using app.run then that would result in an ugly 500 error from the wrapping web server).

The fix is to try to connect to the DB and handle the exception correctly:

try:
    mydb = mysql.connect(
        host="127.0.0.1",              
        user=user_name,
        password=pass_word,
        database = "test_db"
    )
    # ... snip ...
    if not result:
        raise InvalidUserException("Username or password is invalid")
except (InvalidUserException, ProgrammingError):
    return return render_template("login.html", error_statement_wrong="Wrong credentials", user_name=user_name, pass_word=pass_word)

That said, are your users really connecting to the DB with the same credentials that you are storing in the DB for your web app? And are you storing passwords in plain text? (If so, you should learn more about hashing and make sure that you're using a good one-way hash for passwords)

  • Related