From c8117f049603b850a70bdb1823114aa75e3b08b6 Mon Sep 17 00:00:00 2001 From: Alexander Sulfrian Date: Sun, 31 Jan 2016 17:06:31 +0100 Subject: utils/sessions: Automatic permanent sessions --- accounts/__init__.py | 7 ------- accounts/utils/sessions.py | 23 +++++++++++++++-------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/accounts/__init__.py b/accounts/__init__.py index c561fe2..a86974e 100644 --- a/accounts/__init__.py +++ b/accounts/__init__.py @@ -43,10 +43,3 @@ def load_user(user_id): except (current_app.user_backend.NoSuchUserError, current_app.user_backend.InvalidPasswordError): return None - -@app.before_request -def session_permanent(): - if app.config.get('PERMANENT_SESSION_LIFETIME'): - session.permanent = True - else: - session.permanent = False diff --git a/accounts/utils/sessions.py b/accounts/utils/sessions.py index cd12030..dd4e4bb 100644 --- a/accounts/utils/sessions.py +++ b/accounts/utils/sessions.py @@ -24,17 +24,15 @@ class EncryptedSerializer(TaggedJSONSerializer): self.block_size = AES.block_size def _cipher(self, iv): - return AES.new( - current_app.config['SESSION_ENCRYPTION_KEY'], - AES.MODE_CBC, iv) + key = current_app.config['SESSION_ENCRYPTION_KEY'] + assert len(key) == 32 + return AES.new(key, AES.MODE_CBC, iv) def dumps(self, value): """ Encrypt the serialized values with `config.SESSION_ENCRYPTION_KEY`. The key must be 32 bytes long. """ - assert len(current_app.config['SESSION_ENCRYPTION_KEY']) == 32 - serialized_value = super(EncryptedSerializer, self).dumps(value) raw = _pad(serialized_value, self.block_size) @@ -54,9 +52,18 @@ class EncryptedSerializer(TaggedJSONSerializer): class EncryptedSessionInterface(SecureCookieSessionInterface): serializer = EncryptedSerializer() - def open_session(self, *args, **kwargs): + def open_session(self, app, request): + session = None try: parent = super(EncryptedSessionInterface, self) - return parent.open_session(*args, **kwargs) + session = parent.open_session(app, request) except BadPayload: - return self.session_class() + session = self.session_class() + + if session is not None: + if app.config.get('PERMANENT_SESSION_LIFETIME') is not None: + session.permanent = True + else: + session.permanent = False + + return session -- cgit v1.2.3-1-g7c22