Skip to content

Commit

Permalink
fix: delete session metadata cookie (#126)
Browse files Browse the repository at this point in the history
  • Loading branch information
SKairinos authored Jul 23, 2024
1 parent 5f1fb8e commit ab8eb0a
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 2 deletions.
6 changes: 6 additions & 0 deletions codeforlife/middlewares/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
"""
© Ocado Group
Created on 23/07/2024 at 14:28:21(+01:00).
"""

from .session import SessionMiddleware
34 changes: 34 additions & 0 deletions codeforlife/middlewares/session.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""
© Ocado Group
Created on 23/07/2024 at 14:18:28(+01:00).
"""

from django.conf import settings
from django.contrib.sessions.middleware import (
SessionMiddleware as _SessionMiddleware,
)


class SessionMiddleware(_SessionMiddleware):
"""
Override the session middleware to delete the session metadata cookie when
the session key cookie is deleted.
"""

def process_response(self, request, response):
response = super().process_response(request, response)

session = response.cookies.get(settings.SESSION_COOKIE_NAME)
if (
session
and session.get("max-age") == 0
and session.get("expires") == "Thu, 01 Jan 1970 00:00:00 GMT"
):
response.delete_cookie(
key=settings.SESSION_METADATA_COOKIE_NAME,
path=settings.SESSION_COOKIE_PATH,
domain=settings.SESSION_COOKIE_DOMAIN,
samesite=settings.SESSION_COOKIE_SAMESITE,
)

return response
3 changes: 3 additions & 0 deletions codeforlife/settings/custom.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,6 @@
# A global flag to enable/disable sending emails.
# If disabled, emails will be logged to the console instead.
MAIL_ENABLED = bool(int(os.getenv("MAIL_ENABLED", "0")))

# The name of the session metadata cookie.
SESSION_METADATA_COOKIE_NAME = "session_metadata"
2 changes: 1 addition & 1 deletion codeforlife/settings/django.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def get_databases(base_dir: Path): # pragma: no cover
# Application definition

MIDDLEWARE = [
"django.contrib.sessions.middleware.SessionMiddleware",
"codeforlife.middlewares.SessionMiddleware",
"django.middleware.locale.LocaleMiddleware",
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
Expand Down
2 changes: 1 addition & 1 deletion manage.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
]

MIDDLEWARE = [
"django.contrib.sessions.middleware.SessionMiddleware",
"codeforlife.middlewares.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
]
Expand Down

0 comments on commit ab8eb0a

Please sign in to comment.