Step-by-Step Tutorial: Implementing User Login in Flask with Flask-Login

Implementing user login functionality is a fundamental part of many web applications. Flask, a lightweight Python web framework, combined with Flask-Login, makes it straightforward to add user authentication. This tutorial guides you through the process step-by-step.

Prerequisites

  • Python installed on your system
  • Basic knowledge of Flask and Python
  • Flask and Flask-Login installed

Ensure you have Flask and Flask-Login installed. You can install them using pip:

pip install Flask Flask-Login

Creating the Flask Application

Start by setting up a basic Flask app structure.

Create a new Python file, app.py, and import the necessary modules.

from flask import Flask, render_template, redirect, url_for, request

from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user

Initialize the Flask app and Flask-Login.

app = Flask(__name__)

app.secret_key = 'your_secret_key'

login_manager = LoginManager()

login_manager.init_app(app)

Defining the User Model

Create a User class that inherits from UserMixin.

class User(UserMixin):

Define the constructor and user loader function.

users = {'[email protected]': {'password': 'password123', 'id': 1}}

@login_manager.user_loader

def load_user(user_id):

Implement the user loader function.

Creating the Login Route

Define the route to handle login requests.

@app.route('/login', methods=['GET', 'POST'])

Implement the login logic.

Creating the Protected Route

Define a route that requires login.

@app.route('/dashboard')

Decorate with @login_required.

Adding Logout Functionality

Define a route to handle logout.

@app.route('/logout')

Implement the logout logic.

Running the Application

Set the main block to run the Flask app.

if __name__ == '__main__':

app.run(debug=True)

Sample HTML Templates

Create simple HTML templates for login and dashboard pages.

Place them in a templates folder.

login.html

<form method="POST">

<input type="email" name="email" placeholder="Email">

<input type="password" name="password" placeholder="Password">

<button type="submit">Login</button>

</form>

dashboard.html

<h1>Welcome, {{ current_user.id }}!</h1>

<a href=”{{ url_for(‘logout’) }}”>Logout</a>