Custom User Model with Flask-Login#s UserMixin

  • Share this:

Code introduction


This function creates a custom user model class that inherits from Flask-Login's UserMixin and implements several methods related to user authentication.


Technology Stack : Flask-Login, UserMixin

Code Type : Custom function

Code Difficulty : Intermediate


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

def create_user_model():
    # This function creates a custom user model using UserMixin from Flask-Login
    class User(UserMixin):
        def __init__(self, id, username, email):
            self.id = id
            self.username = username
            self.email = email

        def is_authenticated(self):
            # Returns True if the user is authenticated.
            return True

        def is_active(self):
            # Returns True if the user's account is active.
            return True

        def is_anonymous(self):
            # Returns True if the user is anonymous.
            return False

        def get_id(self):
            # Returns the user's unique identifier.
            return str(self.id)

    return User

# JSON representation of the code