Opened 8 months ago

Closed 8 months ago

Last modified 8 months ago

#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


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 Changed 8 months ago by Mariusz Felisiak

Cc: Adam Johnson added
Triage Stage: UnreviewedAccepted

Sounds reasonable.

comment:2 Changed 8 months ago by Adam Johnson

Resolution: wontfix
Status: newclosed

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="")

In [14]: r.cookies["session"]["domain"] = ""

Cookies in response.cookies are http.cookies.Morsel objects:

So you can subclass the existing middleware and override process_response to call super(), then manipulate the cookie before returning the response.

comment:3 Changed 8 months ago by Mariusz Felisiak

Triage Stage: AcceptedUnreviewed

comment:4 in reply to:  2 Changed 8 months ago by Michael Gisi

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.

Note: See TracTickets for help on using tickets.
Back to Top