How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

June 20, 2018
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

“How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS” covers the entire process of creating a login page for our flask application and managing user authentication. This tutorial builds on the User database model that we created in our Flask app in Part 6 of this series that allows us to store user data like username, password, and administrator status in our MySQL database.

1. Power on you Ubuntu 18.04 LTS virtual machine and launch VSCode. Open the folder for first_flask_app and click on the terminal tab in the lower right pane of the application window. Enter the following command to activate the virtual environment:

source activate flask-env

Make sure the prompt in the terminal changes like in the image below.

How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

2. The first and most obvious thing that we need to do is create a form where a user can input information for authentication purposes. To perform this task, we will first need to install a new extension into our virtual environment. The extension that we will install is flask-wtf. Flask-wtf will help us greatly with form validation and rendering, saving us a ton of time and work. To install the extension, enter the following into the terminal:

pip install flask-wtf
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

3. After flask-wtf is installed, we can start our application. Enter the following into the terminal to start the app:

python main.py
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

4. With our application started, we can import the components of the flask-wtf extension that we need. Add the following code to the top of your main.py file to import the components:

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField
from wtforms.validators import DataRequired, email
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

5. Now we will create our login form class. This class will inherit from FlaskForm, so we must pass FlaskForm into our form class. Our login form will authenticate users based on an email and password match, so those will be the fields needed for our form. Add the following code to the Flask app beneath the User model we created in the last tutorial:

class Login_Form(FlaskForm): 
    email = StringField(‘Email’, validators=[DataRequired(), email(‘Please enter a valid email address.’)])
    password = PasswordField(‘Password’, validators=[DataRequired()])
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

6. Now we can create the route for our login page. Beneath the home route, create a route named login that initializes our login form and passes it to a view named login.html by adding the following code:

@app.route(‘/login’, methods=[‘POST’, ‘GET’])
def login(): 
    login_form = Login_Form() 
    return render_template(‘login.html’, title=’Login’, login_form=login_form)
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

7. With our route created, we need to create the login view. Right click on the templates folder for the Flask app in the pane on the left of the application window. Select New File from the dropdown menu and name the new file login.html.

How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

8. The newly created login.html editor opens automatically. Add the following code to the file to extend the base template and present our page heading:

{% extends “base.html” %}
{% block content %}

<h1>Login Page</h1>

{% endblock %}
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

9. Let’s take a look at our new page. Open a web browser and enter the following into the address bar to visit the login view:

127.0.0.1:5000/login
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

10. Before we add the form elements, we need to add some style to our page. Return to VSCode and delete the page heading h1 line.

How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

11. Next, add the following code to structure the login page:

<div class="jumbotron">
     <h1 class="text-center">Login Page</h1>
</div>

<div class="container">
     <div class="container">
         <div class="row">
             <div class="col">

             </div>

             <div class="col">
                 <div class="container">

                 </div>
             </div>

             <div class="col">

             </div>
         </div>
     </div>
</div>
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

12. Before we proceed, we will need to do a few things. First, we need to create a macro file that will help render our form fields. Right click on the templates folder for the Flask app and select New Folder from the dropdown menu. Name the new folder includes.

How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

13. Next, right click on the newly created includes folder and select New File from the dropdown menu. Name the new file _formhelpers.html.

How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

14. To create the macro, add the following code the the _formhelpers.html file and save it:

{% macro render_field(field) %}
    {{ field.label }} 
    {{ field(**kwargs)|safe }}
    {% if field.errors %} 
        {% for error in field.errors %}
            {{ error }}
        {% endfor %}
    {% endif %}
{% endmacro %}
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

15. Return to the login.html tab in VSCode. We will now import the macro that we just created into our login view so that we can use it. Add the following code after {% block content %} at the top of the page:

{% from "includes/_formhelpers.html" import render_field %}
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

16. Finally, we can create our form. Add the following html code in the container div in the middle column of the Bootstrap grid on the login page:

<form action="/login" method="POST">
     <div class="form-group">
        {{ login_form.hidden_tag() }} {{ render_field(login_form.email, class_="form-control") }}
     </div>

     <div class="form-group">
        {{ render_field(login_form.password, class_="form-control") }}
     </div>

     <p class="text-right">
         <input type="submit" class="btn btn-outline-secondary" value="Submit" />
     </p>
</form>
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

17. After saving the files, return to the web browser and refresh the login page. You should see a pretty sweet login form like the one below:

How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

18. If you try to click the Submit button without entering any data into the fields, you will receive validation errors. This means that our form validation is working properly.

How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

19. Return to VSCode and select the main.py file. We now have to create the POST method for the login route. Add the following code to the login route between the login form initialization and the return statement:

if login_form.validate_on_submit():
    email = login_form.email.data
    password = login_form.password.data
    return redirect('/')
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

20. The above code will allow us to enter an email and any password to test our login route and validation. The route will redirect us to the home page if successful. Return to the web browser, enter an email and password and click Submit.

How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

21. As you can see, the login form validation, method, and route all worked correctly since we we redirected to our home page. Now we have to create a user in our database that can actually be authenticated and logged in. Append the following code to the User model in the main.py file. This will allow us to create new users to add to our database.

def __init__(self, email, username, password, is_admin):
    self.email = email
    self.username = username
    self.password = password
    self.is_admin = is_admin
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

22. To do this, stop the Flask application by entering CTRL + C into the terminal, then enter the following command to launch the Python command line interface:

python
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

23. Next, enter the following command to import the modules that we need to create the user:

from main import db, User
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

24. Create a new user object by entering the following command:

new_user = User(“[email protected]”, “jason”, “password123”, False)
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

25. The previous command creates a user with an email of [email protected], a username of jason, a password of password123, and an administrator status of false. We need to add and commit our new user to the database now. To do this, enter the following into the terminal:

db.session.add(new_user)

Then:

db.session.commit()
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

26. Our new user is now added to the database and we can use that account to authenticate. Exit the Python command line interface by entering the following into the terminal:

exit()
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

27. Add the following to the modules that we are importing from flask at the top of the main.py file. This will allow us to flash error and success messages to the users and create sessions for authenticated users:

flash, session

The entire line will look like:

from flask import Flask, request, redirect, render_template, flash, session
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

28. Now open the base.html template file. We need to add the code that will allow our flash messages to appear. Enter the following between the block content and endblock jinja2 tags:

<div>
    {% with messages = get_flashed_messages(with_categories=True) %} 
        {% if messages %}
            {% for category, message in messages %}
                <div class="alert alert-{{category}}">
                    <div class="container">
                        {{message}}
                     </div>
                </div>
            {% endfor %}
        {% endif %}
    {% endwith %}
</div>
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

29. Restart the Flask application. We will now add authentication functionality to the login route. First, the app will search the database for a match to the email that the user enters in the login page. If it finds a match, the matching data object will be retrieved. The Flask app will then compare the password that the user entered to the password that was retrieved with the data object. If the password matches, the user will be authenticated and a session will be created for that user. If the email or password does not match, an error will be issued and the user will not proceed past the login page until he or she enters valid credentials. Between the initialization of the login form and the return statement in the login route, add the following code to authenticate users:

if login_form.validate_on_submit():
    email = login_form.email.data
    password = login_form.password.data

    user = User.query.filter_by(email=email).first()

    if not user:
        flash('Invalid Email', 'danger')
        return redirect('/login')

    if user and user.password != password:
        flash('Invalid Password', 'danger')
        return redirect('login')

    if user and user.password == password:
        session['email'] = email
        session['is_admin'] = user.is_admin
        flash_msg = 'Welcome, ' + user.username.title() + '!'
        flash(flash_msg, 'success')
        return redirect('/')
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

30. Now we can test our application to ensure that authentication is working properly. Enter some random credentials into the login form and enter submit. You should receive and error message like in the image below:

How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

31. Next, attempt to login in with the email that was added with our jason user in step 24. Do not enter the correct password so you can make sure that is working correctly as well.

How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

32. Finally, enter the correct email and password combination for the jason user we created in step 24. You should receive a success message and be redirected to the home page.

How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

33. With the user logged in, any of the routes that we specify are now visible. Now we need to create a route to log the user out. After the login route in the main.py file, enter the following code to create the logout route:

@app.route('/logout')
def logout():

    try:
        del session['email']
        del session['is_admin']
        flash('You have been logged out', 'warning')
        return redirect('/login')

    except KeyError:
        flash("You are not logged in.", "warning")
        return redirect('/login')
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

34. There is one last thing to do before our work is complete. Notice that our home route is still available by entering its address into the browser’s address bar. This defeats the entire purpose of our authentication! In this step, we will remedy the issue. At the bottom of the main.py file, right before “if __name__ == ‘__main__’:,” enter the following code:

@app.before_request
def require_login():

    allowed_routes = ['login']
    if request.endpoint not in allowed_routes and 'email' not in session:
        return redirect('/login')
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

35. The code above will only allow the login view to be available if a user is not authenticated. This means that our home route is no longer accessible unless the user is authenticated and the user’s email is stored in the session. The user will be redirected to the login view otherwise. Let’s test our new fix. Return to your browser and enter the following into the address bar to log the user out and terminate the session:

http://127.0.0.1/logout
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

36. Notice that we received a message indicating that we are logged out and we were also redirected to the login page. To test our authentication, try to visit the application’s home page by entering the following into the browser’s address bar:

http://127.0.0.1/
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

37. Notice that we redirected to the login page. Success! Our user and authentication system has been created. To verify once more, enter the login credentials for the jason object that we created in step 24 and click Submit.

How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

38. This time we are able to view the home page because we are authenticated. Our email and administrator status are stored in the session so that our Flask application can access this information any time that it needs to. Remember, to log out for now you must type the logout route into the address bar of your browser:

http://127.0.0.1/logout
How to Create a Login Page and Manage User Authentication in a Flask Application on Ubuntu 18.04 LTS

The source code for this lesson is available for free on GitHub.