Flask-Login: Managing User Sessions and Authentication in Flask

Table of Contents

  1. Overview
  2. Prerequisites
  3. Installation
  4. Creating the Flask Application
  5. Configuring Flask-Login
  6. Creating the User Model
  7. Creating the Login and Registration Routes
  8. Creating the Login and Registration Forms
  9. Protecting Routes with Authentication
  10. Logging Out
  11. Conclusion

Overview

Flask is a lightweight web framework for building web applications with Python. One common requirement of web applications is user authentication and session management. Flask-Login is a Flask extension that provides a simple way to handle user authentication and manage user sessions.

In this tutorial, we will learn how to use Flask-Login to add authentication to a Flask application. By the end of this tutorial, you will be able to create a login and registration system, protect routes that require authentication, and handle user sessions.

Prerequisites

Before starting this tutorial, you should have a basic understanding of Python and Flask framework. Familiarity with HTML, CSS, and web development concepts is also beneficial.

Installation

To begin, make sure you have Flask and Flask-Login installed. You can install them using pip: bash pip install Flask Flask-Login

Creating the Flask Application

Let’s start by creating a new Flask application. Create a new directory for your project and navigate to it in the terminal. Then, create a new file called app.py and open it in your favorite text editor. ```python from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return 'Hello, Flask-Login!'
``` Save the file and run the Flask application:
```bash
python app.py
``` Visit `http://localhost:5000` in your browser, and you should see the message "Hello, Flask-Login!".

Configuring Flask-Login

Next, we need to configure Flask-Login to work with our application. Add the following code to the app.py file: ```python from flask_login import LoginManager

login_manager = LoginManager()
login_manager.init_app(app)
``` This code initializes a new `LoginManager` object and attaches it to our Flask application. This manager will handle all aspects of user authentication and session management.

Creating the User Model

In order to authenticate users, we need to create a user model. This model represents a user in our application. Let’s create a new file called models.py and define our user model: ```python from flask_login import UserMixin

class User(UserMixin):
    def __init__(self, id):
        self.id = id
``` The `User` class is a basic implementation of the `UserMixin` class provided by Flask-Login. It includes certain required properties and methods for user authentication. In this minimal example, we only have an `id` property, but in a real application, you would have more user-related attributes.

Creating the Login and Registration Routes

Now, let’s create two routes for handling user login and registration. Add the following code to the app.py file: ```python from flask import render_template

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        # Check if username and password are valid
        # Authenticate user
        # Redirect to the protected route
    return render_template('login.html')

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        # Create a new user
        # Redirect to the login page
    return render_template('register.html')
``` These routes handle both GET and POST requests. In the POST section, you would add the logic for validating user credentials, creating a new user, or any other required actions.

Creating the Login and Registration Forms

To collect user input for login and registration, we need to create HTML templates that include the required input fields. Create two new files called login.html and register.html, and add the following code to each file, respectively: html <!-- login.html --> <form method="POST" action="/login"> <input type="text" name="username" placeholder="Username" required> <input type="password" name="password" placeholder="Password" required> <button type="submit">Login</button> </form> html <!-- register.html --> <form method="POST" action="/register"> <input type="text" name="username" placeholder="Username" required> <input type="password" name="password" placeholder="Password" required> <button type="submit">Register</button> </form> These forms include input fields for username and password. The name attribute of each input field corresponds to the variable names used in the login and registration routes.

Protecting Routes with Authentication

Now that we have a login system in place, we can protect certain routes that should only be accessible to authenticated users. To protect a route, we can use the login_required decorator provided by Flask-Login.

Let’s create a protected route that can be accessed only by authenticated users. Add the following code to the app.py file: ```python from flask_login import login_required

@app.route('/protected')
@login_required
def protected():
    return 'Protected Route'
``` The `login_required` decorator ensures that the route can only be accessed by authenticated users. If a user tries to access this route without being logged in, Flask-Login will redirect them to the login page.

Logging Out

Finally, let’s add a logout route that allows users to log out of our application. Add the following code to the app.py file: ```python from flask_login import logout_user

@app.route('/logout')
@login_required
def logout():
    logout_user()
    return 'Logged out successfully'
``` The `logout_user` function provided by Flask-Login will clear the user's session and log them out.

Conclusion

In this tutorial, we have learned how to use Flask-Login to manage user sessions and authentication in a Flask application. We started by creating a Flask application and configuring Flask-Login. Then, we created a user model, implemented login and registration routes, and created corresponding HTML forms. We also learned how to protect certain routes with authentication using the login_required decorator and how to log users out.

By following this tutorial, you now have a basic understanding of how to implement user authentication using Flask-Login. Feel free to explore more features of Flask-Login, such as password hashing, remember me functionality, and user session management.