class AuthCodeHandler
A callable handler class that processes OAuth authentication codes from form POST requests, exchanges them for access tokens, and authenticates users via Azure SSO.
/tf/active/vicechatdev/CDocs/main.py
2837 - 2910
complex
Purpose
This class serves as a webhook/callback handler for OAuth authentication flows. It receives authorization codes via HTTP POST requests, validates them, exchanges them for access tokens using Azure SSO, logs in the user, and returns an HTML response that redirects to the dashboard. It's designed to be used as a Panel server endpoint handler for completing the OAuth authentication flow.
Source Code
class AuthCodeHandler:
"""Handler for processing authentication code from form post."""
def __call__(self, *args, **kwargs):
try:
logger.info("Auth code handler activated")
# Get the request object
request = pn.state.curdoc.session_context.request
# 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 |
|---|---|---|---|
bases |
- | - |
Parameter Details
bases: Inherited base classes (not used in this implementation, appears to be a documentation artifact)
Return Value
The __call__ method returns either: (1) An HTML string containing a success page with auto-redirect meta tag when authentication succeeds, or (2) A dictionary with an 'error' key containing an error message string when authentication fails at any stage. The HTML response triggers a browser redirect to '/' (dashboard) upon successful authentication.
Class Interface
Methods
__call__(self, *args, **kwargs) -> Union[str, Dict[str, str]]
Purpose: Processes OAuth authentication code from POST request, exchanges it for access token, authenticates user, and returns success HTML or error dict
Parameters:
*args: Variable positional arguments (not used but accepted for compatibility)**kwargs: Variable keyword arguments (not used but accepted for compatibility)
Returns: Returns HTML string with auto-redirect on success, or dictionary with 'error' key containing error message string on failure
Dependencies
panelurllib.parseloggingtraceback
Required Imports
import panel as pn
import urllib.parse
import logging
import traceback
Conditional/Optional Imports
These imports are only needed under specific conditions:
import urllib.parse
Condition: imported inside __call__ method for parsing form data
Required (conditional)Usage Example
# Instantiate the handler
auth_handler = AuthCodeHandler()
# Register with Panel server as an endpoint
import panel as pn
pn.serve({'/auth/callback': auth_handler}, port=5006)
# The handler will be automatically called when POST requests arrive
# Typical flow:
# 1. User initiates OAuth login
# 2. Azure redirects to /auth/callback with auth code in POST body
# 3. Handler exchanges code for token
# 4. Handler logs in user via app.login()
# 5. Handler returns HTML that redirects to dashboard
# Manual invocation (for testing):
# result = auth_handler()
# if isinstance(result, dict) and 'error' in result:
# print(f"Error: {result['error']}")
# else:
# print("Success - HTML redirect returned")
Best Practices
- This class should be instantiated once and registered as a Panel server endpoint, not called directly in application code
- Ensure the global 'app' object with azure_sso is initialized before any requests arrive
- The handler expects to be called in a Panel server context with valid session_context available
- Error handling is comprehensive but relies on external logger - ensure logging is configured
- The handler sanitizes auth codes in logs (shows only first/last 5 chars) for security
- Always use HTTPS in production as auth codes are sensitive credentials
- The handler returns HTML for success but dict for errors - calling code should handle both types
- State is not maintained between calls - this is a stateless handler
- The handler depends on external app.login() method succeeding for complete authentication
- POST body must be form-encoded with 'code' parameter containing the authorization code
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function process_auth_code 83.9% similar
-
class SSOCallbackHandler 76.4% similar
-
function auth_callback 76.4% similar
-
function auth_callback_v1 75.9% similar
-
function azure_callback 73.2% similar