Everything you need as a full stack developer

Flask Authentication with user login/logout

- Posted in Flask by

TL;DR Create a Flask project using virtualenv, install Flask-Login extension, set up a User model with SQLAlchemy, implement login functionality with user registration and logout routes.

Flask Authentication with User Login/Logout

In this article, we'll delve into the world of Flask authentication, specifically focusing on implementing user login and logout functionality in a web application built using Flask.

Why Flask?

Flask is a lightweight Python web framework that provides an efficient way to build robust, scalable applications. Its minimalistic design makes it ideal for building small to medium-sized projects. With its extensive collection of extensions, Flask can be easily extended to support complex functionalities such as user authentication.

Project Setup

To begin with, let's set up a new Flask project using the following command:

mkdir flask_auth
cd flask_auth
virtualenv venv
source venv/bin/activate
pip install flask

Next, create a new file named app.py and add the following code to initialize our Flask application:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return "Welcome to my Flask App!"

if __name__ == "__main__":
    app.run(debug=True)

Flask-Login Extension

To implement user authentication in our Flask application, we'll use the Flask-Login extension. This extension provides a simple way to manage user sessions and authentication.

First, install the Flask-Login extension using pip:

pip install flask-login

Next, initialize the Flask-Login extension in our Flask application:

from flask_login import LoginManager

login_manager = LoginManager()
login_manager.init_app(app)

User Model

To store user information, we'll create a simple User model using SQLAlchemy, which is another popular extension for Flask.

First, install Flask-SQLAlchemy:

pip install flask-sqlalchemy

Next, import the necessary modules and define our User model:

from flask_sqlalchemy import SQLAlchemy

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
db = SQLAlchemy(app)

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

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

Login Functionality

Now that we have our User model in place, let's implement the login functionality. We'll create a new route for user registration and another for user login.

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        user = User(username=username, password=password)
        db.session.add(user)
        db.session.commit()
        return "User registered successfully!"

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        user = User.query.filter_by(username=username, password=password).first()
        if user:
            login_user(user)
            return "User logged in successfully!"
    return render_template('login.html')

@app.route('/logout')
def logout():
    logout_user()
    return "User logged out successfully!"

Template Integration

To display the registration and login forms, we'll create two new templates named register.html and login.html.

<!-- register.html -->
<form method="POST">
    <input type="text" name="username" placeholder="Username">
    <input type="password" name="password" placeholder="Password">
    <button type="submit">Register</button>
</form>

<!-- login.html -->
<form method="POST">
    <input type="text" name="username" placeholder="Username">
    <input type="password" name="password" placeholder="Password">
    <button type="submit">Login</button>
</form>

Conclusion

In this article, we've successfully implemented user login and logout functionality in a Flask application using the Flask-Login extension. We've also created a simple User model to store user information.

With these basic authentication features in place, you can now focus on building more complex web applications using Flask.

Example Use Cases

  • Implementing user roles and permissions
  • Integrating with existing authentication systems (e.g., OAuth)
  • Creating password reset functionality

Remember to explore the official documentation for Flask-Login and other extensions to unlock their full potential. Happy coding!

Fullstackist aims to provide immersive and explanatory content for full stack developers Fullstackist aims to provide immersive and explanatory content for full stack developers
Backend Developer 103 Being a Fullstack Developer 107 CSS 109 Devops and Cloud 70 Flask 108 Frontend Developer 357 Fullstack Testing 99 HTML 171 Intermediate Developer 105 JavaScript 206 Junior Developer 124 Laravel 221 React 110 Senior Lead Developer 124 VCS Version Control Systems 99 Vue.js 108

Recent Posts

Web development learning resources and communities for beginners...

TL;DR As a beginner in web development, navigating the vast expanse of online resources can be daunting but with the right resources and communities by your side, you'll be well-equipped to tackle any challenge that comes your way. Unlocking the World of Web Development: Essential Learning Resources and Communities for Beginners As a beginner in web development, navigating the vast expanse of online resources can be daunting. With so many tutorials, courses, and communities vying for attention, it's easy to get lost in the sea of information. But fear not! In this article, we'll guide you through the most valuable learning resources and communities that will help you kickstart your web development journey.

Read more

Understanding component-based architecture for UI development...

Component-based architecture breaks down complex user interfaces into smaller, reusable components, improving modularity, reusability, maintenance, and collaboration in UI development. It allows developers to build, maintain, and update large-scale applications more efficiently by creating independent units that can be used across multiple pages or even applications.

Read more

What is a Single Page Application (SPA) vs a multi-page site?...

Single Page Applications (SPAs) load a single HTML file initially, handling navigation and interactions dynamically with JavaScript, while Multi-Page Sites (MPS) load multiple pages in sequence from the server. SPAs are often preferred for complex applications requiring dynamic updates and real-time data exchange, but MPS may be suitable for simple websites with minimal user interactions.

Read more