Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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'
```
17 changes: 16 additions & 1 deletion src/django_session_timeout/middleware.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import time
import re

from django.conf import settings
from django.contrib.auth.views import redirect_to_login
Expand All @@ -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
Expand Down Expand Up @@ -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()