function login_v2
Flask route handler that displays the login page and redirects authenticated users to the chat interface.
/tf/active/vicechatdev/vice_ai/app.py
651 - 657
simple
Purpose
This function serves as the entry point for user authentication in a Flask web application. It checks if a user is already authenticated and redirects them to the chat page if so. For unauthenticated users, it generates an Azure SSO authentication URL and renders the login template with that URL, enabling users to authenticate via Azure Active Directory.
Source Code
def login():
"""Login page"""
if is_authenticated():
return redirect(url_for('chat'))
auth_url = azure_sso.get_auth_url()
return render_template('login.html', auth_url=auth_url)
Return Value
Returns a Flask Response object. If the user is authenticated, returns a redirect response to the 'chat' route. If not authenticated, returns a rendered HTML template ('login.html') with the Azure SSO authentication URL passed as a template variable named 'auth_url'.
Dependencies
flaskazure_authwerkzeug
Required Imports
from flask import Flask
from flask import render_template
from flask import redirect
from flask import url_for
from auth.azure_auth import AzureSSO
Usage Example
from flask import Flask, render_template, redirect, url_for
from auth.azure_auth import AzureSSO
app = Flask(__name__)
azure_sso = AzureSSO(client_id='your-client-id', tenant_id='your-tenant-id', redirect_uri='http://localhost:5000/callback')
def is_authenticated():
from flask import session
return 'user_id' in session
@app.route('/login')
def login():
if is_authenticated():
return redirect(url_for('chat'))
auth_url = azure_sso.get_auth_url()
return render_template('login.html', auth_url=auth_url)
@app.route('/chat')
def chat():
return 'Chat page'
if __name__ == '__main__':
app.run(debug=True)
Best Practices
- Ensure the is_authenticated() function properly validates user session state to prevent unauthorized access
- The azure_sso object must be properly initialized with valid Azure AD credentials before this route is accessed
- Implement proper error handling for cases where azure_sso.get_auth_url() might fail
- Ensure the login.html template properly handles and displays the auth_url for user authentication
- Consider adding CSRF protection to the login flow
- Implement rate limiting on the login route to prevent brute force attacks
- Use HTTPS in production to protect authentication credentials in transit
- Ensure the 'chat' route has proper authentication checks to prevent direct access
- Consider adding logging for login attempts for security auditing purposes
Tags
Similar Components
AI-powered semantic similarity - components with related functionality: