🔍 Code Extractor

function require_auth_v1

Maturity: 39

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.

File:
/tf/active/vicechatdev/vice_ai/complex_app.py
Lines:
508 - 515
Complexity:
simple

Purpose

This decorator is used to protect Flask routes that require user authentication. It wraps route handler functions and intercepts requests to verify authentication status via the is_authenticated() function. If the user is not authenticated, it redirects them to the login page. If authenticated, it allows the original function to execute normally. This is a common pattern in web applications for implementing authorization middleware.

Source Code

def require_auth(f):
    """Decorator to require authentication"""
    def decorated_function(*args, **kwargs):
        if not is_authenticated():
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    decorated_function.__name__ = f.__name__
    return decorated_function

Parameters

Name Type Default Kind
f - - positional_or_keyword

Parameter Details

f: The Flask route handler function to be decorated. This should be a callable that handles HTTP requests for a specific route. The decorator will wrap this function to add authentication checking before execution.

Return Value

Returns a decorated function that wraps the original function 'f'. When called, the decorated function first checks authentication status. If not authenticated, it returns a Flask redirect response to the 'login' route. If authenticated, it returns the result of calling the original function 'f' with all passed arguments and keyword arguments.

Dependencies

  • flask

Required Imports

from flask import redirect
from flask import url_for

Usage Example

from flask import Flask, session, redirect, url_for

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

def is_authenticated():
    return session.get('user_id') is not None

def require_auth(f):
    def decorated_function(*args, **kwargs):
        if not is_authenticated():
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    decorated_function.__name__ = f.__name__
    return decorated_function

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

@app.route('/protected')
@require_auth
def protected_route():
    return 'This is a protected page'

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

Best Practices

  • Ensure the is_authenticated() function is properly implemented to check session or token validity
  • The decorator preserves the original function name using __name__ assignment, but consider using functools.wraps for more complete metadata preservation
  • Place @require_auth decorator below @app.route() decorator when using with Flask routes
  • Ensure Flask session is properly configured with a secret key for session-based authentication
  • Consider implementing flash messages before redirect to inform users why they were redirected to login
  • For production use, consider using established libraries like Flask-Login instead of custom authentication decorators
  • The is_authenticated() function should be lightweight as it's called on every request to protected routes

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function require_auth 97.7% 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_required 89.7% similar

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

    From: /tf/active/vicechatdev/docchat/app.py
  • function is_authenticated 67.4% similar

    Checks if a user is authenticated by verifying the presence of 'user' and 'access_token' keys in the Flask session object.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function login 65.4% 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 login_v2 64.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