🔍 Code Extractor

function login_v1

Maturity: 48

Flask route handler that manages user authentication by redirecting authenticated users to the index page, initiating Azure SSO login for production, or creating a development session for local testing.

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
398 - 425
Complexity:
moderate

Purpose

This function serves as the login endpoint for a Flask web application. It checks if the user is already authenticated and redirects them to the index page if so. For production environments with Azure SSO configured, it dynamically builds a redirect URI based on request headers (supporting proxy/load balancer scenarios) and generates an Azure authentication URL. For development environments without Azure SSO, it creates a mock user session with development credentials and redirects to the index page.

Source Code

def login():
    """Login page"""
    if is_authenticated():
        return redirect(url_for('index'))
    
    if AZURE_SSO_AVAILABLE:
        # Build dynamic redirect URI based on current request
        scheme = request.headers.get('X-Forwarded-Proto', request.scheme)
        host = request.headers.get('X-Forwarded-Host', request.host)
        dynamic_redirect_uri = f"{scheme}://{host}/auth/callback"
        
        # Temporarily update the redirect_uri for this request
        original_redirect = azure_sso.redirect_uri
        azure_sso.redirect_uri = dynamic_redirect_uri
        auth_url = azure_sso.get_auth_url()
        azure_sso.redirect_uri = original_redirect  # Restore original
        
        return render_template('login.html', auth_url=auth_url)
    else:
        # Fallback for development
        session.permanent = True  # Make session persistent
        session['user'] = {
            'name': 'Development User',
            'email': 'dev@example.com',
            'login_time': datetime.now().isoformat()
        }
        session['access_token'] = 'dev-token'
        return redirect(url_for('index'))

Return Value

Returns a Flask response object. If the user is already authenticated, returns a redirect to the 'index' route. If Azure SSO is available, returns a rendered 'login.html' template with the Azure authentication URL. If Azure SSO is not available (development mode), creates a session with mock user data and returns a redirect to the 'index' route.

Dependencies

  • flask
  • datetime

Required Imports

from flask import render_template
from flask import request
from flask import session
from flask import redirect
from flask import url_for
from datetime import datetime

Conditional/Optional Imports

These imports are only needed under specific conditions:

from auth.azure_auth import AzureSSO

Condition: Required if Azure SSO authentication is enabled (AZURE_SSO_AVAILABLE is True)

Optional

Usage Example

# In your Flask application file:
from flask import Flask, render_template, request, session, redirect, url_for
from datetime import datetime
from auth.azure_auth import AzureSSO

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

# Configuration
AZURE_SSO_AVAILABLE = True  # Set to False for development
azure_sso = AzureSSO(client_id='your-client-id', tenant_id='your-tenant-id', redirect_uri='https://yourapp.com/auth/callback')

def is_authenticated():
    return 'user' in session and 'access_token' in session

@app.route('/login')
def login():
    if is_authenticated():
        return redirect(url_for('index'))
    
    if AZURE_SSO_AVAILABLE:
        scheme = request.headers.get('X-Forwarded-Proto', request.scheme)
        host = request.headers.get('X-Forwarded-Host', request.host)
        dynamic_redirect_uri = f"{scheme}://{host}/auth/callback"
        
        original_redirect = azure_sso.redirect_uri
        azure_sso.redirect_uri = dynamic_redirect_uri
        auth_url = azure_sso.get_auth_url()
        azure_sso.redirect_uri = original_redirect
        
        return render_template('login.html', auth_url=auth_url)
    else:
        session.permanent = True
        session['user'] = {
            'name': 'Development User',
            'email': 'dev@example.com',
            'login_time': datetime.now().isoformat()
        }
        session['access_token'] = 'dev-token'
        return redirect(url_for('index'))

@app.route('/')
def index():
    return 'Welcome to the app!'

if __name__ == '__main__':
    app.run(debug=True)

Best Practices

  • The function dynamically builds redirect URIs to support deployment behind proxies or load balancers by checking X-Forwarded-Proto and X-Forwarded-Host headers
  • Always restore the original azure_sso.redirect_uri after temporarily modifying it to avoid side effects
  • Use session.permanent = True to ensure sessions persist across browser restarts when appropriate
  • The development fallback should only be used in non-production environments; ensure AZURE_SSO_AVAILABLE is properly configured based on environment
  • Store sensitive session data securely and consider using secure session cookies in production
  • The is_authenticated() helper function should be consistently used across all protected routes
  • Consider implementing session timeout and refresh mechanisms for better security
  • The login.html template should handle the auth_url parameter and provide a clear login button or automatic redirect
  • Ensure the 'index' route exists and is properly configured before deploying this login function

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function login_v2 91.5% similar

    Flask route handler that displays the login page and redirects authenticated users to the chat interface.

    From: /tf/active/vicechatdev/vice_ai/app.py
  • function login 89.9% 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 login_v3 89.5% similar

    Flask route handler that displays the login page and redirects authenticated users to the document workspace.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function logout_v1 79.8% similar

    Flask route handler that logs out the current user by clearing their session data and redirecting them to the login page.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function index_v4 77.2% similar

    Flask route handler for the root URL ('/') that redirects authenticated users to the document workspace and unauthenticated users to the login page.

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