🔍 Code Extractor

function login_required

Maturity: 46

A Flask decorator that enforces authentication requirements on routes by checking for user session data and redirecting unauthenticated users to the login page.

File:
/tf/active/vicechatdev/docchat/app.py
Lines:
56 - 69
Complexity:
simple

Purpose

This decorator provides route-level authentication protection in Flask applications. It checks if authentication is required via configuration, verifies the presence of a user in the session, and redirects to the login page if authentication fails. It allows bypassing authentication when REQUIRE_AUTH is disabled in the configuration, making it useful for development or optional authentication scenarios.

Source Code

def login_required(f):
    """Decorator to require authentication for routes"""
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not config.REQUIRE_AUTH:
            # If auth is disabled, allow access
            return f(*args, **kwargs)
        
        if 'user' not in session:
            # User not logged in, redirect to login
            return redirect(url_for('login'))
        
        return f(*args, **kwargs)
    return decorated_function

Parameters

Name Type Default Kind
f - - positional_or_keyword

Parameter Details

f: The Flask route function to be decorated. This should be a view function that handles HTTP requests and returns a response. The decorator will wrap this function with authentication logic.

Return Value

Returns a decorated function that wraps the original route function. When called, it either: (1) executes the original function if authentication passes or is disabled, (2) returns a redirect response to the login page if the user is not authenticated. The return type matches whatever the decorated function returns (typically a Flask Response object).

Dependencies

  • flask
  • functools

Required Imports

from flask import session
from flask import redirect
from flask import url_for
from functools import wraps
import config

Usage Example

from flask import Flask, session, redirect, url_for
from functools import wraps
import config

app = Flask(__name__)
app.secret_key = 'your-secret-key'

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not config.REQUIRE_AUTH:
            return f(*args, **kwargs)
        if 'user' not in session:
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    return decorated_function

@app.route('/login')
def login():
    session['user'] = 'example_user'
    return 'Logged in'

@app.route('/protected')
@login_required
def protected_route():
    return f'Hello {session["user"]}! This is a protected route.'

@app.route('/public')
def public_route():
    return 'This route is accessible to everyone'

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

Best Practices

  • Always apply this decorator after the @app.route() decorator to ensure proper route registration
  • Ensure Flask session is properly configured with a SECRET_KEY before using this decorator
  • The 'login' route name must exist in your Flask application or url_for('login') will raise a BuildError
  • Set config.REQUIRE_AUTH appropriately for your environment (False for development, True for production)
  • Store minimal user information in the session; use user IDs rather than full user objects
  • Consider implementing session timeout mechanisms alongside this decorator for enhanced security
  • Use @wraps(f) to preserve the original function's metadata (name, docstring) for proper Flask routing
  • For API endpoints, consider using a different authentication mechanism (like token-based auth) instead of session-based redirects

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function require_auth_v1 89.7% similar

    A Flask decorator that enforces authentication by checking if a user is authenticated before allowing access to a protected route, redirecting to login if not authenticated.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function require_auth 86.3% similar

    A decorator function that enforces authentication requirements on Flask route handlers by checking if a user is authenticated before allowing access to the decorated function.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function login 72.5% similar

    Flask route handler that renders the login page for user authentication, with support for Azure SSO integration and automatic redirection for authenticated users or when authentication is disabled.

    From: /tf/active/vicechatdev/docchat/app.py
  • function logout 70.3% similar

    Flask route handler that logs out the current user by clearing their session and redirecting them to either the login page or index page based on authentication requirements.

    From: /tf/active/vicechatdev/docchat/app.py
  • function login_v2 70.2% similar

    Flask route handler that displays the login page and redirects authenticated users to the chat interface.

    From: /tf/active/vicechatdev/vice_ai/app.py
← Back to Browse