From 4986ee865e342d39163312bf10c824d3870158f1 Mon Sep 17 00:00:00 2001 From: Hanne Moa Date: Wed, 6 Mar 2024 13:54:46 +0100 Subject: [PATCH] Vendor the PickleSerializer --- python/nav/django/settings.py | 2 +- python/nav/web/session_serializer.py | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 python/nav/web/session_serializer.py diff --git a/python/nav/django/settings.py b/python/nav/django/settings.py index d9aacb4ef5..da04da10e0 100644 --- a/python/nav/django/settings.py +++ b/python/nav/django/settings.py @@ -135,7 +135,7 @@ 'django.contrib.messages.middleware.MessageMiddleware', ) -SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer' +SESSION_SERIALIZER = 'nav.web.session_serializer.PickleSerializer' SESSION_ENGINE = 'django.contrib.sessions.backends.db' SESSION_COOKIE_AGE = int(_webfront_config.get('sessions', {}).get('timeout', 3600)) SESSION_COOKIE_NAME = 'nav_sessionid' diff --git a/python/nav/web/session_serializer.py b/python/nav/web/session_serializer.py new file mode 100644 index 0000000000..98fefec8b9 --- /dev/null +++ b/python/nav/web/session_serializer.py @@ -0,0 +1,24 @@ +import pickle + +from django.conf import settings +from django.core.exceptions import ImproperlyConfigured + + +class PickleSerializer: + """ + Simple wrapper around pickle to be used in signing.dumps()/loads() and + cache backends. + """ + + def __init__(self, protocol=None): + if settings.SESSION_ENGINE == 'django.contrib.sessions.backends.signed_cookies': + raise ImproperlyConfigured( + "PickleSerializer cannot be used with signed_cookies SESSION_ENGINE" + ) + self.protocol = pickle.HIGHEST_PROTOCOL if protocol is None else protocol + + def dumps(self, obj): + return pickle.dumps(obj, self.protocol) + + def loads(self, data): + return pickle.loads(data)