CORS Middleware

class smarter.lib.django.middleware.cors.SmarterCorsMiddleware(get_response)[source]

Bases: CorsMiddleware, SmarterHelperMixin

Middleware for handling Cross-Origin Resource Sharing (CORS) headers in the application.

This middleware extends the default CORS handling to dynamically add chatbot URLs to the allowed origins at runtime. It ensures that requests from valid chatbot origins are permitted by updating the CORS allowed origins list based on the current request context.

The middleware also provides additional logic to handle internal IP addresses, health check endpoints, and logging for debugging and auditing purposes.

Variables:
  • _url (Optional[SplitResult]) – The parsed URL (as a urllib.parse.SplitResult) for the current request, or None.

  • _chatbot (Optional[ChatBot]) – The chatbot instance associated with the current request, or None.

  • request (Optional[HttpRequest]) – The current Django HTTP request object, or None.

Key Features

  • Dynamically adds chatbot URLs to the CORS allowed origins list.

  • Handles requests from internal IP addresses and health check endpoints.

  • Provides detailed logging for CORS-related events and decisions.

  • Integrates with Django and the django-cors-headers package.

Note

  • The chatbot URL is only added to the allowed origins if a chatbot is associated with the request.

  • Internal requests and health checks are short-circuited for efficiency.

  • Logging is controlled via a waffle switch and the application’s log level.

Example

To enable this middleware, add it to your Django project’s middleware settings:

MIDDLEWARE = [
    ...
    'smarter.lib.django.middleware.cors.SmarterCorsMiddleware',
    ...
]
Parameters:

request (django.http.HttpRequest) – The incoming HTTP request object.

Returns:

The HTTP response object, potentially with CORS headers added.

Return type:

django.http.response.HttpResponseBase or Awaitable[HttpResponseBase]

property CORS_ALLOWED_ORIGINS: list[str] | tuple[str][source]

Returns the list of allowed origins for the application. If the request is from a chatbot, the chatbot url is added to the list. If the host is an api.local.smarter.sh domain, allow localhost for development.

property formatted_class_name: str

Return the formatted class name for logging purposes.