Backend Middleware

Backend Middleware

Source of truth:

  • Middleware list: backend/config/settings.py (MIDDLEWARE)
  • Implementations:
    • backend/apps/common/middleware.py
    • backend/apps/tenants/middleware.py

Ordering (What Runs When)

Relevant highlights from MIDDLEWARE:

  • whitenoise.middleware.WhiteNoiseMiddleware serves static assets.
  • corsheaders.middleware.CorsMiddleware must run early for cross-origin requests.
  • django.contrib.sessions.middleware.SessionMiddleware enables cookie sessions.
  • django.middleware.csrf.CsrfViewMiddleware enforces CSRF for cookie-authenticated unsafe methods.
  • django.contrib.auth.middleware.AuthenticationMiddleware populates request.user.
  • apps.tenants.middleware.TenantMiddleware selects an active tenant and sets thread-local context.
  • apps.tenants.middleware.TenantRequiredMiddleware returns 409 TENANT_REQUIRED for authenticated API calls without an active tenant.

SecurityScannerBlockerMiddleware

apps.common.middleware.SecurityScannerBlockerMiddleware detects common scanner probes (e.g. /.env, /wp-admin) and blocks abusive IPs using Django cache (Redis in production).

TenantRequiredMiddleware (API-only)

This middleware is intentionally API-only:

  • No redirects (returns JSON)
  • Allows /_allauth/ for login/signup
  • Allows /api/v1/workspaces so the user can create/select a workspace

Implementation: backend/apps/tenants/middleware.py.

Last updated June 21, 2026