Flask User Authentication - Includes Free Sample
Hello! This article explains how to code a Flask User Authentication system using Flask-Login
and Bootstrap 5
. Being able to distinguish one user from another web apps can be improved substantially in terms of features and control. For instance, we can split the project structure into public/private sections and also empower users to perform specific actions based on their profiles. For newcomers, Flask is a lightweight framework crafted on top of Python used for any kind of project and web apps: simple sites, APIs, microservices, or even complex eCommerce solutions.
Thanks for reading! Topics covered by this tutorial:
- Section #1 - The general view of the project
- Section #2 - What is Flask
- Section #3 -
Flask-Login
library - Section #4 - Code the project
- Section #5 - Login, Logout, Registration routes
- Section #6 - Full Source code (published on Github)
1# - Project Overview
Authentication might not be necessary for simple presentation sites but mandatory for other types of projects where the project design requires to know when a user is authenticated and what resources to be accessed based on his credentials (username, profiles .. etc). The project we will code provides a simple codebase structure, SQLite persistence, and three pages (index, login, register) styled with Bootstrap 5. Here are the project dependencies:
Flask
- the framework that powers the appFlask-Login
- a popular library used to manage the sessionsFlask-Bcrypt
- used for password encryptionFlask-SqlAlchemy
- a popular library to access the database
Codebase structure
2# - What is Flask
Flask is a popular Python Framework designed to a project quick and easy, with the ability to scale up to complex applications. Flask can be used to code from simple one-page sites to APIs and complex eCommerce solutions.
The easiest way to install Flask is to use PIP, the official package manager shipped with Python.
During the setup, a basic set of core dependencies are also installed:
- Werkzeug implements WSGI, the standard Python interface between applications and servers.
- Jinja is a template language that renders the pages your application serves.
- Click is a framework for writing command-line applications. It provides the flask command and allows adding custom management commands.
Once the installation is finished we can open an editor and code our first Flask app with a few lines of code:
#3 - Flask-Login Library
Flask-Login
, probably the most popular authentication library for Flask, provides user session management and handles the common tasks of logging in, logging out, and remembering your users’ sessions over extended periods of time.
Install Flask-Login
The most important part of an application that uses Flask-Login is the LoginManager class.
Once the Flask application object has been created, you can configure it for login with a single line:
How it Works
The app needs to provide a user_loader
callback. This callback is used to reload the user object from the user ID stored in the session.
The above core principles of Flask-Login
cover the basic implementation of a simple authentication system that we will code in full in the next section.
#4 - Coding the project
Before we actually code the features, let's visualize again the structure and mention the most relevant files:
run.py
- is the entry point in our projectapp
directory bundles all files and assets used in our projectapp/config.py
- isolates the app configuration in a single placeapp/forms.py
- definesSignIN
,SignUP
formsapp/models.py
- defines the Users tableapp/views.py
- handles the app routing likelogin
,logout
andregister
run.py
- source code
The file is a super simple loader of the APP
package.
app/config.py
- APP Configuration
For easier access, all variables are exposed by a Config
class:
The SECRET_KEY
variable is used to encrypt the session information and SQLALCHEMY_DATABASE_URI
is used to locate the SQLite database (basically a file).
app/forms.py
- Login and registration forms
The login form requires a username and a password to authenticate and the registration form has an extra email field.
app/models.py
Defined theUsers
table
All above sections are bundled to build the Flask app in a special file saved in the app
directory: "__init__.py"
#5 - Authentication routes
All app routes are provided by the app/views.py
file saved in app
directory.
/register
route - handles the onboarding of the new users
The pseudocode implemented by the method is pretty simple:
- If the request type is
GET
, serve the registration page to the user - If the user submitted the information, the method performs the checks
- Once the data is validated, the
User
password is hashed - The
User
object is created and saved into the database
/login
route - authenticate registered users
/logout
route - delete the session data associated to the user
6# - Full Source Code
The source code explained in this article can be downloaded from Github (MIT license) and used for hobby and commercial projects.
Flask User Authentication - source code
To compile and start the project locally, please follow the instructions provided by the README file.
Thanks for reading! For more resources, please access:
- Flask Dashboards - free & commercial products
- Free Admin Dashboards - a curated list provided by AppSeed