Flask Login View Function: Handling User Authentication

  • Share this:

Code introduction


This code block defines a Flask login view function that handles the login process. It checks if the current user is authenticated, and if not, simulates the user logging in.


Technology Stack : Flask, Flask-Login

Code Type : Flask Login Function

Code Difficulty : Intermediate


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

class User(UserMixin):
    def __init__(self, id):
        self.id = id

# Initialize the login manager
login_manager = LoginManager()
login_manager.init_app(app)

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

def login_view():
    # This function handles the login process
    if current_user.is_authenticated:
        return 'You are already logged in', 200
    else:
        # Simulate a user trying to log in
        user = User('1')
        login_user(user)
        return 'Logged in successfully', 200

# Flask app initialization (simulated)
app = Flask(__name__)
app.secret_key = 'your_secret_key'