From 0bdc7e737091c737a01b990ed93c38412a2704fb Mon Sep 17 00:00:00 2001 From: Harris Tzovanakis Date: Thu, 21 Nov 2019 10:43:27 +0100 Subject: [PATCH] sessions: addition of KVSession interface Signed-off-by: Harris Tzovanakis --- invenio_accounts/config.py | 4 ++++ invenio_accounts/sessions.py | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/invenio_accounts/config.py b/invenio_accounts/config.py index 78664a6d..cb5b54f9 100644 --- a/invenio_accounts/config.py +++ b/invenio_accounts/config.py @@ -223,3 +223,7 @@ ACCOUNTS_USERINFO_HEADERS = False """If True, add X-Session-ID and X-User-ID to the HTTP response.""" + +SESSION_INTERFACE_FACTORY = \ + 'invenio_accounts.sessions:KVSessionInterfaceWithAnonymousSessions' +"""Set the session interface factory for KVSession""" diff --git a/invenio_accounts/sessions.py b/invenio_accounts/sessions.py index 799f4cd8..b80e7bec 100644 --- a/invenio_accounts/sessions.py +++ b/invenio_accounts/sessions.py @@ -17,6 +17,8 @@ from __future__ import absolute_import, print_function from flask import after_this_request, current_app, request, session +from flask_kvsession import KVSessionInterface +from flask_login import current_user from geolite2 import geolite2 from invenio_db import db from ua_parser import user_agent_parser @@ -135,3 +137,20 @@ def delete_user_sessions(user): SessionActivity.query.filter_by(user=user).delete() return True + + +class KVSessionInterfaceWithAnonymousSessions(KVSessionInterface): + """Session interface to avoid storing anonymous sessions.""" + + def save_session(self, app, session, response): + """Save session interface.""" + anonymous_session = not current_user.is_authenticated + super( + KVSessionInterfaceWithAnonymousSessions, + self + ).save_session( + app, + session, + response, + anonymous_session=anonymous_session + )