function index_v3
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.
/tf/active/vicechatdev/vice_ai/app.py
644 - 648
simple
Purpose
This function acts as a routing controller for the root URL ('/') of a Flask web application. It implements authentication-based navigation by checking the user's authentication status and redirecting them to the appropriate page. This is a common pattern in web applications to ensure users land on the correct page based on their login state, preventing unauthorized access to protected resources while providing a seamless user experience.
Source Code
def index():
"""Main page - redirect to chat if authenticated, otherwise login"""
if is_authenticated():
return redirect(url_for('chat'))
return redirect(url_for('login'))
Return Value
Returns a Flask redirect response object. If the user is authenticated (is_authenticated() returns True), it redirects to the 'chat' route using url_for('chat'). If the user is not authenticated, it redirects to the 'login' route using url_for('login'). The redirect function returns a werkzeug.wrappers.Response object with a 302 status code by default.
Dependencies
flask
Required Imports
from flask import Flask
from flask import redirect
from flask import url_for
Usage Example
from flask import Flask, redirect, url_for, session
app = Flask(__name__)
app.secret_key = 'your-secret-key-here'
def is_authenticated():
return session.get('user_id') is not None
@app.route('/')
def index():
if is_authenticated():
return redirect(url_for('chat'))
return redirect(url_for('login'))
@app.route('/login')
def login():
return 'Login Page'
@app.route('/chat')
def chat():
return 'Chat Page'
if __name__ == '__main__':
app.run(debug=True)
Best Practices
- Ensure is_authenticated() function is properly implemented and handles edge cases like expired sessions
- The 'chat' and 'login' routes must exist in the application, otherwise url_for() will raise a BuildError
- Consider adding error handling for cases where url_for() might fail
- This pattern prevents direct access to protected routes by always checking authentication at the root level
- Make sure Flask's secret_key is set if using session-based authentication
- Consider using Flask-Login or similar authentication extensions for more robust authentication management
- For production environments, ensure HTTPS is enabled to protect authentication credentials
- Add logging to track authentication attempts and redirects for security monitoring
Tags
Similar Components
AI-powered semantic similarity - components with related functionality: