Flask

User Login and Authentication with Flask


Introduction

User login and authentication are essential components of web applications that require user-specific features and security. In this guide, we'll explore how to implement user login and authentication in Flask, a Python web framework. You'll learn how to create login forms, securely authenticate users, manage user sessions, and protect restricted routes.

Step 1: Setting Up Your Flask Application

Before you can implement user login and authentication, make sure you have a Flask application. If not, you can create a basic Flask app like this:

from flask import Flask, render_template, request, redirect, url_for, session
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
app = Flask(__name)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///your_database.db'
app.config['SECRET_KEY'] = 'your_secret_key'
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
        

Ensure you have Flask-SQLAlchemy, Flask-Bcrypt, and specify the database URI for your SQLite database. Set a secret key for session management.

Step 2: Creating a User Model

Define a model for user data. Here's an example of a simple model for a `User` with a username and hashed password:

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True, nullable=False)
    password = db.Column(db.String(60), nullable=False)
        

This model represents user data with fields for `id,` `username,` and a hashed `password.`

Step 3: Creating a Login Form

Create a login form using HTML and add it to your template. Here's an example of a simple login form:

<form method=`POST` action=`/login`>
    <label for=`username`>Username:</label>
    <input type=`text` id=`username` name=`username` required>
    <br>
    <label for=`password`>Password:</label>
    <input type=`password` id=`password` name=`password` required>
    <br>
    <input type=`submit` value=`Login`>
</form>
        

Create a route in your Flask app to render the form and handle user login.

Step 4: Handling User Login

Create a route to handle user login and authenticate users. Here's an example route for login:

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        # Authenticate user (e.g., using Flask-Bcrypt)
        user = User.query.filter_by(username=username).first()
        if user and bcrypt.check_password_hash(user.password, password):
            session['user_id'] = user.id
            return redirect(url_for('dashboard'))
    return render_template('login.html')
        

In this example, the route processes the login form data and authenticates the user using Flask-Bcrypt for password hashing. If the login is successful, the user session is created.

Step 5: Protecting Restricted Routes

Use Flask's @login_required decorator to protect routes that should only be accessible to logged-in users.

Step 6: Logging Out

Create a route for user logout, and clear the session to log the user out.

@app.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('login'))
        

Step 7: Running Your Application

As usual, run your Flask application with the following code at the end of your script:

if __name__ == '__main__':
    app.run()
        

Now, you can run your application with the command python your_app.py and access the login and protected routes.

Conclusion

Implementing user login and authentication in Flask is crucial for building secure web applications. By following these steps, you can create a user authentication system that allows users to log in, protects restricted routes, and ensures data privacy.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.