🔍 Code Extractor

function process_auth_code

Maturity: 51

Processes OAuth authorization codes from POST requests, exchanges them for access tokens via Azure SSO, and authenticates users into the application.

File:
/tf/active/vicechatdev/CDocs/main.py
Lines:
2993 - 3061
Complexity:
moderate

Purpose

This function serves as an OAuth callback handler that receives authorization codes from JavaScript POST requests, validates the request method, extracts the auth code from form data, exchanges it for an access token using Azure SSO, logs the user into the application, and returns either a success HTML page with redirect or error messages. It's a critical component in the OAuth authentication flow for Azure SSO integration.

Source Code

def process_auth_code(request, *args, **kwargs):
    """Process the auth code from JavaScript POST request"""
    try:
        logger.info("Auth code handler activated")
        
        # Check if this is a POST request
        if request.method != "POST":
            logger.error("Auth code handler received non-POST request")
            return {"error": "Invalid request method"}
        
        # Parse the request body as form data
        import urllib.parse
        form_data = dict(urllib.parse.parse_qsl(request.body.decode('utf-8')))
        
        # Get the auth code
        auth_code = form_data.get('code')
        if not auth_code:
            logger.error("No auth code found in form data")
            return {"error": "No authorization code provided"}
        
        # Log sanitized version of the code
        sanitized_code = auth_code[:5] + "..." + auth_code[-5:] if len(auth_code) > 10 else "***"
        logger.info(f"Received auth code: {sanitized_code}")
        
        # Exchange code for token
        try:
            if not hasattr(app, 'azure_sso') or not app.azure_sso:
                logger.error("Azure SSO not initialized")
                return {"error": "SSO authentication is not configured"}
            
            token_response = app.azure_sso.get_token_from_code(auth_code)
            
            if not token_response or 'access_token' not in token_response:
                logger.error("Failed to exchange auth code for token")
                return {"error": "Failed to exchange authorization code for token"}
            
            # Log success
            logger.info("Successfully exchanged auth code for token")
            
            # Login the user
            success = app.login(username=None, sso_token=token_response)
            if not success:
                logger.error("Login failed with token")
                return {"error": "Authentication failed"}
            
            # Return success HTML
            html = """
            <html>
            <head>
                <title>Authentication Successful</title>
                <meta http-equiv="refresh" content="0;url=/" />
            </head>
            <body>
                <h1>Authentication Successful</h1>
                <p>Redirecting to dashboard...</p>
            </body>
            </html>
            """
            return html
            
        except Exception as e:
            logger.error(f"Error processing auth code: {e}")
            logger.error(traceback.format_exc())
            return {"error": f"Error processing authentication: {str(e)}"}
        
    except Exception as e:
        logger.error(f"Error in auth code handler: {e}")
        logger.error(traceback.format_exc())
        return {"error": f"Internal server error: {str(e)}"}

Parameters

Name Type Default Kind
request - - positional_or_keyword
*args - - var_positional
**kwargs - - var_keyword

Parameter Details

request: HTTP request object containing the POST data with the authorization code. Expected to have 'method' attribute and 'body' attribute with URL-encoded form data containing a 'code' parameter.

*args: Variable length argument list for additional positional arguments (not used in current implementation but allows for flexible function signatures).

**kwargs: Arbitrary keyword arguments for additional named parameters (not used in current implementation but allows for flexible function signatures).

Return Value

Returns either a dictionary with an 'error' key containing error messages (dict[str, str]) when authentication fails or validation errors occur, or an HTML string containing a success page with meta refresh redirect to '/' when authentication succeeds. The HTML includes a title, auto-redirect, and user-friendly success message.

Dependencies

  • urllib.parse
  • logging
  • traceback
  • panel

Required Imports

import urllib.parse
import logging
import traceback

Conditional/Optional Imports

These imports are only needed under specific conditions:

import urllib.parse

Condition: imported inside the function to parse form data from request body

Required (conditional)

Usage Example

# This function is typically used as a route handler in a web framework
# Example setup:
import logging
logger = logging.getLogger(__name__)

# Mock request object for demonstration
class MockRequest:
    def __init__(self, method, body):
        self.method = method
        self.body = body

# Mock app object with Azure SSO
class MockApp:
    def __init__(self):
        self.azure_sso = MockAzureSSO()
    
    def login(self, username=None, sso_token=None):
        return True if sso_token else False

class MockAzureSSO:
    def get_token_from_code(self, code):
        return {'access_token': 'mock_token_12345'}

app = MockApp()

# Simulate POST request with auth code
auth_code = 'authorization_code_from_oauth_provider'
request_body = f'code={auth_code}'.encode('utf-8')
request = MockRequest('POST', request_body)

# Process the auth code
result = process_auth_code(request)

# Result will be HTML string on success or error dict on failure
if isinstance(result, dict) and 'error' in result:
    print(f"Authentication failed: {result['error']}")
else:
    print("Authentication successful, user will be redirected")

Best Practices

  • Ensure the global 'app' object is properly initialized with azure_sso attribute before calling this function
  • Configure proper logging to track authentication attempts and failures
  • The function sanitizes auth codes in logs (showing only first and last 5 characters) to prevent credential leakage
  • Always use HTTPS in production to protect authorization codes in transit
  • Implement rate limiting on this endpoint to prevent brute force attacks
  • The function expects URL-encoded form data in the request body, not JSON
  • Error messages are returned as dictionaries while success returns HTML - handle both response types appropriately
  • The success HTML includes a meta refresh redirect to '/' - ensure this path is appropriate for your application
  • Consider implementing CSRF protection for this POST endpoint
  • The function relies on app.login() method - ensure this method properly establishes user sessions

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class AuthCodeHandler 83.9% similar

    A callable handler class that processes OAuth authentication codes from form POST requests, exchanges them for access tokens, and authenticates users via Azure SSO.

    From: /tf/active/vicechatdev/CDocs/main.py
  • function auth_callback_v1 76.9% similar

    OAuth2 callback handler for Azure SSO authentication that processes authorization codes, exchanges them for access tokens, and establishes user sessions.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function auth_callback 76.7% similar

    OAuth callback handler that processes Azure SSO authentication responses, exchanges authorization codes for access tokens, and establishes user sessions.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function azure_callback 74.8% similar

    OAuth 2.0 callback endpoint for Azure AD authentication that exchanges authorization codes for access tokens and establishes user sessions.

    From: /tf/active/vicechatdev/docchat/app.py
  • function auth_callback_v2 72.9% similar

    Flask route handler that processes OAuth 2.0 callback from Azure AD, exchanges authorization code for access tokens, and establishes user session.

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