🔍 Code Extractor

function require_auth

Maturity: 46

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.

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
370 - 379
Complexity:
simple

Purpose

This decorator is used to protect Flask routes that require user authentication. When applied to a route handler, it intercepts the request, checks authentication status via the is_authenticated() function, and either redirects unauthenticated users to the login page or allows authenticated users to proceed to the protected route. This is a common pattern in web applications for implementing authorization middleware.

Source Code

def require_auth(f):
    """Decorator to require authentication"""
    from functools import wraps
    
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not is_authenticated():
            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 function to be decorated, typically a Flask route handler. This should be a callable that handles HTTP requests and returns a Flask response object. The decorator will wrap this function with authentication checking logic.

Return Value

Returns a decorated function (decorated_function) that wraps the original function f. When called, this wrapper first checks authentication status. If authenticated, it returns the result of calling f(*args, **kwargs). If not authenticated, it returns a Flask redirect response to the 'login' route. The decorator preserves the original function's metadata using @wraps.

Dependencies

  • flask
  • functools

Required Imports

from functools import wraps
from flask import redirect, url_for

Conditional/Optional Imports

These imports are only needed under specific conditions:

from functools import wraps

Condition: imported inside the decorator function itself (lazy import)

Required (conditional)

Usage Example

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

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

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

def require_auth(f):
    from functools import wraps
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not is_authenticated():
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    return decorated_function

@app.route('/login')
def login():
    session['user_id'] = 123
    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 defined before using this decorator
  • The decorator should be applied closest to the function definition (innermost decorator if using multiple decorators)
  • Make sure a 'login' route exists in your Flask application, otherwise url_for('login') will raise a BuildError
  • Consider adding flash messages before redirecting to inform users why they were redirected
  • For API endpoints, consider returning JSON error responses instead of redirects
  • The decorator uses @wraps(f) to preserve the original function's metadata, which is important for Flask's routing system
  • This decorator should be used in conjunction with proper session management and secure authentication mechanisms
  • Consider implementing CSRF protection and secure session cookies in production environments

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function require_auth_v1 97.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 login_required 86.3% 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.2% 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 60.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 index_v3 59.4% similar

    Flask route handler that serves as the application's main entry point, redirecting users to either the chat page if authenticated or the login page if not.

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