function require_auth
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.
/tf/active/vicechatdev/vice_ai/new_app.py
370 - 379
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
flaskfunctools
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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function require_auth_v1 97.7% similar
-
function login_required 86.3% similar
-
function is_authenticated 67.2% similar
-
function login 60.5% similar
-
function index_v3 59.4% similar