Skip to content

Commit daa75f6

Browse files
committed
Implement SESSION_TIMEOUT_REDIRECT
This implements #9 but in a slightly more robust way. Thanks https://github.com/millerthegorilla
1 parent 1b84887 commit daa75f6

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,9 @@ To group by different period use the following setting:
4848
```python
4949
SESSION_EXPIRE_AFTER_LAST_ACTIVITY_GRACE_PERIOD = 60 # group by minute
5050
```
51+
52+
To redirect to a custom URL define the following setting:
53+
54+
```python
55+
SESSION_TIMEOUT_REDIRECT = 'your_redirect_url_here/'
56+
```

src/django_session_timeout/middleware.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from django.conf import settings
44
from django.contrib.auth.views import redirect_to_login
5+
from django.shortcuts import redirect
56

67
try:
78
from django.utils.deprecation import MiddlewareMixin
@@ -27,7 +28,11 @@ def process_request(self, request):
2728

2829
if session_is_expired:
2930
request.session.flush()
30-
return redirect_to_login(next=request.path)
31+
redirect_url = getattr(settings, "SESSION_TIMEOUT_REDIRECT", None)
32+
if redirect_url:
33+
return redirect(redirect_url)
34+
else:
35+
return redirect_to_login(next=request.path)
3136

3237
expire_since_last_activity = getattr(
3338
settings, "SESSION_EXPIRE_AFTER_LAST_ACTIVITY", False

tests/test_middleware.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,19 @@ def test_session_expire(r, settings):
4949
assert response["location"] == "/accounts/login/?next=/"
5050

5151

52+
def test_session_expire_custom_redirect(r, settings):
53+
settings.SESSION_EXPIRE_SECONDS = 3600
54+
settings.SESSION_TIMEOUT_REDIRECT = "/foobar/"
55+
middleware = SessionTimeoutMiddleware()
56+
57+
with freeze_time("2017-08-31 21:46:00"):
58+
assert middleware.process_request(r) is None
59+
60+
with freeze_time("2017-08-31 22:46:01"):
61+
response = middleware.process_request(r)
62+
assert response["location"] == "/foobar/"
63+
64+
5265
def test_session_expire_no_expire_setting(r, settings):
5366
settings.SESSION_COOKIE_AGE = 3600
5467
middleware = SessionTimeoutMiddleware()

0 commit comments

Comments
 (0)