Only add sessions refresh data to existing sessions

Prior to change session were created for _every_ request (including API
requests).
This commit is contained in:
Christopher C. Wells 2021-08-05 06:34:08 -07:00
parent 207a5bc236
commit f29269869c
1 changed files with 12 additions and 11 deletions

View File

@ -26,21 +26,22 @@ class UserTimezoneMiddleware:
class RollingSessionMiddleware: class RollingSessionMiddleware:
""" """
Periodically resets the session expiry. Periodically resets the session expiry for existing sessions.
""" """
def __init__(self, get_response): def __init__(self, get_response):
self.get_response = get_response self.get_response = get_response
def __call__(self, request): def __call__(self, request):
session_refresh = request.session.get('session_refresh') if request.session.keys():
if session_refresh: session_refresh = request.session.get('session_refresh')
try: if session_refresh:
delta = int(time.time()) - session_refresh try:
except (ValueError, TypeError): delta = int(time.time()) - session_refresh
delta = settings.ROLLING_SESSION_REFRESH + 1 except (ValueError, TypeError):
if delta > settings.ROLLING_SESSION_REFRESH: delta = settings.ROLLING_SESSION_REFRESH + 1
if delta > settings.ROLLING_SESSION_REFRESH:
request.session['session_refresh'] = int(time.time())
request.session.set_expiry(settings.SESSION_COOKIE_AGE)
else:
request.session['session_refresh'] = int(time.time()) request.session['session_refresh'] = int(time.time())
request.session.set_expiry(settings.SESSION_COOKIE_AGE)
else:
request.session['session_refresh'] = int(time.time())
return self.get_response(request) return self.get_response(request)