In the last Flask tutorial, we covered a login page for our users to log in with, but we quickly found that we weren't handling the data that the user had input to the form. In this tutorial, we're going to cover how to do that!
Here's our new login function, which is a part of the __init__.py file.
@app.route('/login/', methods=["GET","POST"]) def login_page(): error = '' try: if request.method == "POST": attempted_username = request.form['username'] attempted_password = request.form['password'] #flash(attempted_username) #flash(attempted_password) if attempted_username == "admin" and attempted_password == "password": return redirect(url_for('dashboard')) else: error = "Invalid credentials. Try Again." return render_template("login.html", error = error) except Exception as e: #flash(e) return render_template("login.html", error = error)
Now what we do is first see if the request.method was a POST method. Before we attempt to handle a request, we have to see if there even was one. Keep in mind that someone may have either just submitted a log in attempt, or maybe they just simply loaded the login page and then are going to log in.
So, we check to see if there was a POST. If so, then we're going to look for what the user put into the username and password fields. Since we don't quite yet have a database of users, we're just going to hard code an acceptable user and their password. In this case, we're only going to accept the user called admin with a password of password.
If that is what the user entered, great, we'll call them logged in and send them to the dashboard. If not, we're going to say the error is "Invalid credentials. Try again." This way, if they enter the wrong information, the login.html template is still loaded, but they see a reason why.
So we have some very basic logic now that will handle the request, and compare it to acceptable data to allow a login. This is a very impractical method for handling user information, as well as being very insecure. Now we want some users. To get users, we actually need a way for users to register. In order for users to register, we're going to need a database set up to store their credentials. Let's do that!