From 4a2cb747c16dc58af39b1ae56e1cf14dfeb9c9a7 Mon Sep 17 00:00:00 2001 From: Vincenzo Castiglia Date: Thu, 23 May 2019 15:45:38 +0200 Subject: [PATCH] fix issue #173 Session cookie expiration isn't locale-safe (#174) * fix issue #173 Session cookie expiration isn't locale-safe --- .travis.yml | 5 +++++ beaker/session.py | 15 ++++++++++++++- tests/test_cookie_expires.py | 11 +++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 19ec61b8..dfc32726 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,6 +2,11 @@ language: python os: - linux dist: xenial +addons: + apt: + packages: + - language-pack-it + - locales services: - mongodb - memcached diff --git a/beaker/session.py b/beaker/session.py index 7a6d63e0..f3f6f4a9 100644 --- a/beaker/session.py +++ b/beaker/session.py @@ -9,6 +9,12 @@ from beaker.exceptions import BeakerException, InvalidCryptoBackendError from beaker.cookie import SimpleCookie + +months = (None, "Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") +weekdays = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") + + __all__ = ['SignedCookie', 'Session', 'InvalidSignature'] @@ -281,6 +287,13 @@ def _set_cookie_values(self, expires=None): self._set_cookie_expires(expires) + @staticmethod + def serialize_cookie_date(v): + v = v.timetuple() + r = time.strftime("%%s, %d-%%s-%Y %H:%M:%S GMT", v) + return r % (weekdays[v[6]], months[v[1]]) + + def _set_cookie_expires(self, expires): if expires is None: expires = self.cookie_expires @@ -300,7 +313,7 @@ def _set_cookie_expires(self, expires): self.cookie[self.key]['expires'] = '' return True self.cookie[self.key]['expires'] = \ - expires_date.strftime("%a, %d-%b-%Y %H:%M:%S GMT") + self.serialize_cookie_date(expires_date) return expires_date def _update_cookie_out(self, set_cookie=True): diff --git a/tests/test_cookie_expires.py b/tests/test_cookie_expires.py index 7b95ac80..3423dadd 100644 --- a/tests/test_cookie_expires.py +++ b/tests/test_cookie_expires.py @@ -56,6 +56,17 @@ def test_cookie_exprires_2(): assert no_expires is False, no_expires +def test_cookie_expires_different_locale(): + from locale import setlocale, LC_TIME + expires_date = datetime.datetime(2019, 5, 22) + setlocale(LC_TIME, 'it_IT.UTF-8') + # if you get locale.Error: unsupported locale setting. you have to enable that locale in your OS. + assert expires_date.strftime("%a, %d-%b-%Y %H:%M:%S GMT").startswith('mer,') + session = Session({}, cookie_expires=True, validate_key='validate_key') + assert session._set_cookie_expires(expires_date) + expires = cookie_expiration(session) + assert expires == 'Wed, 22-May-2019 00:00:00 GMT', expires + setlocale(LC_TIME, '') # restore default locale for further tests def test_set_cookie_expires(): """Exhibit Set-Cookie: values."""