Flask-Login User Authentication and Protection

  • Share this:

Code introduction


This code snippet demonstrates how to use functionalities from the Flask-Login library to protect views, ensuring that users must be logged in to access them. It defines a function named `login_required_view` that checks if the user is authenticated, and if not, it redirects to the login page. It also uses the `login_required` decorator to protect another view function, ensuring that only authenticated users can access it.


Technology Stack : Flask-Login

Code Type : Flask-Login Function

Code Difficulty : Intermediate


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

class User(UserMixin):
    # This is a simple User class that inherits from UserMixin, which provides default implementations
    # for methods that Flask-Login expects user objects to have.
    def __init__(self, id):
        self.id = id

def login_required_view():
    # This function checks if the user is logged in, if not it redirects to the login page.
    if not current_user.is_authenticated:
        return redirect(url_for('login', next=request.url))
    
    # The login_required decorator can also be used directly on the view function.
    @login_required
    def view_function():
        return 'You are now logged in as %s' % current_user.id

    return view_function()                
              
Tags: