function login_required
A Flask decorator that enforces authentication requirements on routes by checking for user session data and redirecting unauthenticated users to the login page.
/tf/active/vicechatdev/docchat/app.py
56 - 69
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
flaskfunctools
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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function require_auth_v1 89.7% similar
-
function require_auth 86.3% similar
-
function login 72.5% similar
-
function logout 70.3% similar
-
function login_v2 70.2% similar