The rest of the middleware commit

This commit is contained in:
Peter Hardy 2020-05-17 20:11:08 +10:00
parent 1d9a7d4215
commit 2806d0a22f
3 changed files with 19 additions and 1 deletions

View File

@ -23,6 +23,7 @@ class UserTimezoneMiddleware:
pass pass
return self.get_response(request) return self.get_response(request)
class RollingSessionMiddleware: class RollingSessionMiddleware:
""" """
Periodically resets the session expiry. Periodically resets the session expiry.
@ -35,7 +36,7 @@ class RollingSessionMiddleware:
if session_refresh: if session_refresh:
try: try:
delta = int(time.time()) - session_refresh delta = int(time.time()) - session_refresh
except: except (ValueError, TypeError):
delta = settings.ROLLING_SESSION_REFRESH + 1 delta = settings.ROLLING_SESSION_REFRESH + 1
if delta > settings.ROLLING_SESSION_REFRESH: if delta > settings.ROLLING_SESSION_REFRESH:
request.session['session_refresh'] = int(time.time()) request.session['session_refresh'] = int(time.time())

View File

@ -35,3 +35,5 @@ REST_FRAMEWORK['DEFAULT_RENDERER_CLASSES'] = (
'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer', 'rest_framework.renderers.BrowsableAPIRenderer',
) )
ROLLING_SESSION_REFRESH = 1

View File

@ -1,4 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import time
from django.test import TestCase from django.test import TestCase
from django.test import Client as HttpClient from django.test import Client as HttpClient
from django.contrib.auth.models import User from django.contrib.auth.models import User
@ -30,6 +32,19 @@ class ViewsTestCase(TestCase):
page = self.c.get('/') page = self.c.get('/')
self.assertEqual(page.url, '/dashboard/') self.assertEqual(page.url, '/dashboard/')
def test_rolling_sessions(self):
self.c.get('/')
session1 = str(self.c.cookies['sessionid'])
# Sleep longer than ROLLING_SESSION_REFRESH in our
# settings module, to test we get a new session.
time.sleep(2)
self.c.get('/')
session2 = str(self.c.cookies['sessionid'])
self.c.get('/')
session3 = str(self.c.cookies['sessionid'])
self.assertNotEqual(session1, session2)
self.assertEqual(session2, session3)
def test_user_reset_api_key(self): def test_user_reset_api_key(self):
api_key_before = User.objects.get(pk=self.user.id).settings.api_key() api_key_before = User.objects.get(pk=self.user.id).settings.api_key()
page = self.c.get('/user/reset-api-key/') page = self.c.get('/user/reset-api-key/')