Opened 2 years ago

Closed 2 years ago

Last modified 2 years 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

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 Mariusz Felisiak, 2 years ago

Cc: Adam Johnson added
Triage Stage: UnreviewedAccepted

Sounds reasonable.

comment:2 by Adam Johnson, 2 years ago

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="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 Mariusz Felisiak, 2 years ago

Triage Stage: AcceptedUnreviewed

in reply to:  2 comment:4 by Michael Gisi, 2 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.

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