Smarter Middleware Mixin

class smarter.common.mixins.SmarterMiddlewareMixin(get_response, *args, **kwargs)[source]

Bases: SmarterHelperMixin

A mixin for middleware classes with helper functions. The initialization is a blatant copy of Django 6x cors middleware. This this is our base case for working with ASGI and sync middlewares.

This mixin provides utilities for extracting client IP addresses, checking authentication indicators, and other middleware-related helpers. Inherits from SmarterHelperMixin.

Adds a smarter_process_id attribute to the request which is helpful for caching and logging to correlate logs across the same request flow, especially in async contexts where thread-local storage is not reliable.

__init__(get_response, *args, **kwargs)[source]

Note: this needs to exist.

something in the Python MRO requires it, even if it does nothing. If you remove this, you will get a mysterious error about something downstream expecting exactly one object.

get_client_ip(request)[source]

Get client IP address from request.

This method attempts to determine the original client IP address, accounting for proxies, load balancers, and CDNs. It checks common headers set by proxies and falls back to REMOTE_ADDR.

Notes

  • In AWS CLB → Kubernetes Nginx setups, the client IP flow is: Client → CLB → Nginx Ingress → Django. - CLB adds X-Forwarded-For with the original client IP. - Nginx may add X-Real-IP or modify X-Forwarded-For. - Django sees REMOTE_ADDR as the Nginx IP (not the client IP).

  • If using Cloudflare, it adds the CF-Connecting-IP header.

  • Always validate IPs to avoid trusting spoofed headers.

Parameters:

request (HttpRequest) – The Django request object.

Returns:

The detected client IP address, or None if not found.

Return type:

Optional[str]

has_auth_indicators(request)[source]

Check if request has authentication indicators (cookies, headers, etc.).

This method inspects the request for common authentication signals, such as session cookies, CSRF tokens, authorization headers, API keys, or Django’s built-in authentication.

Parameters:

request (HttpRequest) – The Django request object.

Returns:

True if authentication indicators are present, False otherwise.

Return type:

bool

set_smarter_process_id(request)[source]

Set smarter_process_id on request if not already set. This has to consider the pipeline of middlewares. Each middleware class sets its own unique smarter_process_id, but if a previous middleware has already set the request object’s smarter_process_id then we should not overwrite it. This allows all middlewares in the pipeline to share the same process ID for logging and caching purposes.

Return type:

None

smarter_process_id: int