module

DjangoMiddlewareGuard

A project middleware in settings.MIDDLEWARE that turns an unauthenticated request away (a login redirect, a 401/403) unless its path is exempt. It is judged by its definition: its __call__ (or process_request) is walked for an anonymous caller at the endpoint's path and verb, and it guards the endpoint when every way through that serves the view needs a logged-in caller.

Conditions evaluate to T / F, Choice (the caller decides: a query parameter, or a path test the endpoint's <path:...> placeholder may or may not satisfy) or Unknown (a setting, a test this cannot read). A view served only behind an Unknown keeps the guard, with a note.

Constants

BLOCK_KEYWORD = /\A(?:if|elif|else|for|while|with|try|except|finally|async\s+with|async\s+for)\b/
MW_ANONYMOUS_FAILS = /\buser\.(?:is_authenticated|is_staff|is_superuser|is_active)\b|\bhas_perms?\s*\(|\bauthenticate\s*\(/

What only a logged-in caller passes: AnonymousUser is never staff, active or permitted.

MW_CALLER_INPUT = /\brequest\.(?:GET|POST|COOKIES|headers|META|query_params|data|body|FILES|session)\b/
MW_CREDENTIAL_ABSENT = /\bnot\s+in\b|\bis\s+None\b|==\s*None\b/
MW_CREDENTIAL_NAME = /['"](?:HTTP_)?[\w-]*(?:key|token|secret|signature|password|authorization)[\w-]*['"]/i
MW_CREDENTIAL_SOURCE = /\brequest\.(?:headers|META|COOKIES)\b/

A credential the caller sends in a header or cookie, which an anonymous caller does not have.

MW_IDENTITY = /\b(?:is_authenticated|is_anonymous)\b/
MW_LOGIN_REDIRECT = /\b(?:HttpResponseRedirect|redirect)\s*\(.*(?:log_?in|sign_?in)/i

HttpResponseRedirect(settings.LOGIN_URL), redirect(reverse("account_login")).

MW_PATH_EXPR = /(?<![\w.])request\.(?:path_info|path|get_full_path\(\s*\))(?:\[\s*:\s*\d+\s*\])?/

The request path itself. A [:N] slice only truncates it; any other transform (lstrip, [1:], split, lower) is not the path.

MW_SETTING_READ = /\bsettings\.[A-Z]|\bos\.(?:environ|getenv)\b|\bgetenv\s*\(/
MW_STRING = /\A[rRfFbBuU]{0,2}(['"])(.*)\1\z/
ROOT_URLCONF = /^ROOT_URLCONF\s*=\s*['"]([\w.]+)['"]/m

Nested types