From f93abaff139bd868621dfcd463da2bc918a3309b Mon Sep 17 00:00:00 2001 From: ewoudenberg-kasisto Date: Tue, 17 Aug 2021 15:15:57 -0400 Subject: [PATCH] Add ability to ignore certain URL paths when determining whether there is activity. --- README.md | 6 ++++++ src/django_session_timeout/middleware.py | 17 ++++++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 0e5863f..b6797d4 100644 --- a/README.md +++ b/README.md @@ -54,3 +54,9 @@ To redirect to a custom URL define the following setting: ```python SESSION_TIMEOUT_REDIRECT = 'your_redirect_url_here/' ``` + +To ignore URL paths that are not considered "activity" (such as those used when browser code is regularly polling for status) put a regular expression matching the paths to be ignored in the following setting: + +```python +SESSION_ACTIVITY_IGNORED_PATHS_REGEX = '/first/ignored/path|/another/ignored/path' +``` diff --git a/src/django_session_timeout/middleware.py b/src/django_session_timeout/middleware.py index bda7fcb..69493bb 100644 --- a/src/django_session_timeout/middleware.py +++ b/src/django_session_timeout/middleware.py @@ -1,4 +1,5 @@ import time +import re from django.conf import settings from django.contrib.auth.views import redirect_to_login @@ -14,6 +15,18 @@ class SessionTimeoutMiddleware(MiddlewareMixin): + def __init__(self, get_response=None): + self.get_response = get_response + self.ignored_paths_regex = None + + regex = getattr(settings, "SESSION_ACTIVITY_IGNORED_PATHS_REGEX", None) + if regex: + self.ignored_paths_regex = re.compile(regex) + + def is_path_ignored(self, path): + ignored = self.ignored_paths_regex and bool(self.ignored_paths_regex.search(path)) + return ignored + def process_request(self, request): if not hasattr(request, "session") or request.session.is_empty(): return @@ -41,5 +54,7 @@ def process_request(self, request): settings, "SESSION_EXPIRE_AFTER_LAST_ACTIVITY_GRACE_PERIOD", 1 ) - if expire_since_last_activity and time.time() - init_time > grace_period: + if expire_since_last_activity \ + and time.time() - init_time > grace_period \ + and not self.is_path_ignored(request.path): request.session[SESSION_TIMEOUT_KEY] = time.time()