#34073 closed Cleanup/optimization (wontfix)
Refactor session middleware to allow easier overrides
| Reported by: | Michael Gisi | Owned by: | nobody |
|---|---|---|---|
| Component: | contrib.sessions | Version: | 4.1 |
| Severity: | Normal | Keywords: | middleware |
| Cc: | Adam Johnson | Triage Stage: | Unreviewed |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
I've recently needed to manipulate the session cookie domain per-request. In order to do so, I needed to create a new middleware class inheriting from SessionMiddleware, overriding the process_response method.
Because the middleware logic reads the domain directly from settings, the result is a largely copy-pasted method just to change the domain being set on the cookie. This override is also liable to break if the middleware or settings change in future Django releases.
In contrast, SecurityMiddleware was much easier to override, since any settings are loaded as instance attributes in __init__.
The proposed solution would consist of loading settings in the session middleware __init__ e.g. self.cookie_domain = settings.SESSION_COOKIE_DOMAIN.
Happy to submit a PR if this seems reasonable.
Change History (4)
comment:1 by , 3 years ago
| Cc: | added |
|---|---|
| Triage Stage: | Unreviewed → Accepted |
follow-up: 4 comment:2 by , 3 years ago
| Resolution: | → wontfix |
|---|---|
| Status: | new → closed |
Copying from settings in __init__ will mean that tests using override_settings to replace the values will no longer work.
You can manipulate the domain of a cookie after it's set:
In [11]: from django.http import HttpResponse
In [12]: r = HttpResponse()
In [13]: r.set_cookie("session", "123", domain="example.com")
In [14]: r.cookies["session"]["domain"] = "example.org"
Cookies in response.cookies are http.cookies.Morsel objects: https://docs.python.org/3.10/library/http.cookies.html#http.cookies.Morsel
So you can subclass the existing middleware and override process_response to call super(), then manipulate the cookie before returning the response.
comment:3 by , 3 years ago
| Triage Stage: | Accepted → Unreviewed |
|---|
comment:4 by , 3 years ago
Replying to Adam Johnson:
Got it, I hadn't considered the effect on tests or the ability to modify cookies after calling set_cookie. Thank you for your detailed response, cheers.
Sounds reasonable.