Skip to content
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
567bd91
fix: session ID stability while maintaining inactivity timeout
ttak-apphelix Jun 12, 2025
f4a3d74
fix: linter issue
ttak-apphelix Jun 13, 2025
79dd8f9
Merge branch 'openedx:master' into ttak/session_id_fix
ttak-apphelix Jun 17, 2025
b5f4baf
fix!: session ID stability while maintaining inactivity timeout
ttak-apphelix Jun 17, 2025
8dd5bd2
fix!: session ID stability while maintaining inactivity timeout
ttak-apphelix Jun 17, 2025
f953ed9
Merge branch 'openedx:master' into ttak/session_id_fix
ttak-apphelix Jun 20, 2025
4f2ca29
fix: update session inactivity middleware to use consistent naming an…
ttak-apphelix Jun 20, 2025
50a212c
Merge branch 'openedx:master' into ttak/session_id_fix
ttak-apphelix Jun 25, 2025
02c0114
fix: correct logging variable name and improve log levels in session …
ttak-apphelix Jun 25, 2025
e50ede8
Merge branch 'openedx:master' into ttak/session_id_fix
ttak-apphelix Jun 26, 2025
43e0842
fix: enhance session inactivity tracking with TieredCache and custom …
ttak-apphelix Jun 26, 2025
8b935b1
Merge branch 'openedx:master' into ttak/session_id_fix
ttak-apphelix Jul 3, 2025
81f043f
fix: update session inactivity tracking to use user-specific cache ke…
ttak-apphelix Jul 3, 2025
9f42295
Merge branch 'openedx:master' into ttak/session_id_fix
ttak-apphelix Jul 8, 2025
c801c23
fix: simplify session save time key handling and improve logging for …
ttak-apphelix Jul 8, 2025
25a339f
fix: remove unused last session save time key and streamline session …
ttak-apphelix Jul 8, 2025
988d8c2
Merge branch 'openedx:master' into ttak/session_id_fix
ttak-apphelix Jul 25, 2025
495e2d6
fix: enhance session inactivity tracking with improved logging and er…
ttak-apphelix Jul 25, 2025
cdb462c
Merge branch 'openedx:master' into ttak/session_id_fix
ttak-apphelix Jul 28, 2025
6bdf73f
fix: linting fix
ttak-apphelix Jul 28, 2025
4334bac
Merge branch 'openedx:master' into ttak/session_id_fix
ttak-apphelix Jul 30, 2025
4cf4f90
Merge branch 'openedx:master' into ttak/session_id_fix
ttak-apphelix Aug 1, 2025
c666449
fix: enhance session inactivity monitoring with improved error handling
ttak-apphelix Aug 1, 2025
47ca3b4
fix: fix linter and import
ttak-apphelix Aug 1, 2025
385eb3f
Merge branch 'openedx:master' into ttak/session_id_fix
ttak-apphelix Aug 8, 2025
21d1b29
fix: incorporated review comment
ttak-apphelix Aug 14, 2025
3adcbe0
Merge branch 'openedx:master' into ttak/session_id_fix
ttak-apphelix Aug 14, 2025
b18b107
fix: removed unwanted comments
ttak-apphelix Aug 14, 2025
567dd9a
fix: updated mock for log
ttak-apphelix Aug 14, 2025
e282383
Merge branch 'openedx:master' into ttak/session_id_fix
ttak-apphelix Aug 18, 2025
68f1514
fix!: session ID stability while maintaining inactivity timeout
ttak-apphelix Aug 18, 2025
390fd8b
fixup! Update openedx/core/djangoapps/session_inactivity_timeout/test…
robrap Aug 21, 2025
040cfef
Merge branch 'master' into ttak/session_id_fix
robrap Aug 21, 2025
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
74 changes: 60 additions & 14 deletions openedx/core/djangoapps/session_inactivity_timeout/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,18 @@


from datetime import datetime, timedelta
import logging

from django.conf import settings
from django.contrib import auth
from django.utils.deprecation import MiddlewareMixin
from edx_django_utils import monitoring as monitoring_utils
from edx_django_utils.cache import TieredCache

LAST_TOUCH_KEYNAME = 'SessionInactivityTimeout:last_touch'
LAST_TOUCH_KEYNAME = 'SessionInactivityTimeout:last_touch_str'
LAST_SESSION_SAVE_TIME_KEYNAME = 'SessionInactivityTimeout:last_session_save_time'

log = logging.getLogger(__name__)


class SessionInactivityTimeout(MiddlewareMixin):
Expand All @@ -34,27 +40,67 @@ def process_request(self, request):
#Can't log out if not logged in
return

# .. setting_name: SESSION_INACTIVITY_TIMEOUT_IN_SECONDS
# .. setting_default: None
# .. setting_description: If set, this is used to end the session when there is no activity for N seconds.
# .. setting_warning: Keep in sync with SESSION_COOKIE_AGE and must be larger than SESSION_ACTIVITY_SAVE_DELAY_SECONDS.
timeout_in_seconds = getattr(settings, "SESSION_INACTIVITY_TIMEOUT_IN_SECONDS", None)

# Do we have this feature enabled?
if timeout_in_seconds:
# .. setting_name: SESSION_ACTIVITY_SAVE_DELAY_SECONDS
# .. setting_default: 900 (15 minutes in seconds)
# .. setting_description: How often to allow a full session save (in seconds).
# This controls how frequently the session ID might change.
# A user could be inactive for almost SESSION_ACTIVITY_SAVE_DELAY_SECONDS but since their session
# isn't being saved during that time, their last activity timestamp isn't being updated.
# When they hit the inactivity timeout, it will be based on the last saved activity time.
# So the effective timeout could be as short as: SESSION_INACTIVITY_TIMEOUT_IN_SECONDS - SESSION_ACTIVITY_SAVE_DELAY_SECONDS.
# This means users might be logged out earlier than expected in some edge cases.
# .. setting_warning: Must be smaller than SESSION_INACTIVITY_TIMEOUT_IN_SECONDS.
frequency_time_in_seconds = getattr(settings, "SESSION_ACTIVITY_SAVE_DELAY_SECONDS", 900)
# what time is it now?
utc_now = datetime.utcnow()
Comment thread
robrap marked this conversation as resolved.
Outdated

# Get the last time user made a request to server, which is stored in session data
last_touch = request.session.get(LAST_TOUCH_KEYNAME)
last_touch_str = request.session.get(LAST_TOUCH_KEYNAME)
Comment thread
robrap marked this conversation as resolved.

# have we stored a 'last visited' in session? NOTE: first time access after login
# this key will not be present in the session data
if last_touch:
# compute the delta since last time user came to the server
time_since_last_activity = utc_now - last_touch

# did we exceed the timeout limit?
if time_since_last_activity > timedelta(seconds=timeout_in_seconds):
# yes? Then log the user out
del request.session[LAST_TOUCH_KEYNAME]
auth.logout(request)
return

request.session[LAST_TOUCH_KEYNAME] = utc_now
if last_touch_str:
try:
last_touch = datetime.fromisoformat(last_touch_str)
time_since_last_activity = utc_now - last_touch

has_exceeded_timeout_limit = time_since_last_activity > timedelta(seconds=timeout_in_seconds)
Comment thread
robrap marked this conversation as resolved.
if has_exceeded_timeout_limit:
del request.session[LAST_TOUCH_KEYNAME]
auth.logout(request)
return
except (ValueError, TypeError) as e:
log.warning("Parsing last touch time failed: %s", e)
Comment thread
robrap marked this conversation as resolved.
# If parsing fails, treat as if no timestamp exists
pass
Comment thread
robrap marked this conversation as resolved.
Outdated
Comment thread
robrap marked this conversation as resolved.
Outdated
else:
# .. custom_attribute_name: session_inactivity.first_login
# .. custom_attribute_description: Tracks when users have no stored activity
# timestamp (first access after login).
monitoring_utils.set_custom_attribute('session_inactivity.first_login', True)
Comment thread
robrap marked this conversation as resolved.
Comment thread
robrap marked this conversation as resolved.
log.debug("No previous activity timestamp found (first login)")

cached_response = TieredCache.get_cached_response(LAST_SESSION_SAVE_TIME_KEYNAME)
Comment thread
robrap marked this conversation as resolved.
Outdated
Comment thread
robrap marked this conversation as resolved.
Outdated
last_save = cached_response.value if cached_response.is_found else None
current_time = datetime.utcnow().isoformat()
Comment thread
robrap marked this conversation as resolved.
Outdated

# .. custom_attribute_name: session_inactivity.activity_seen
# .. custom_attribute_description: Records the timestamp when user activity is detected.
monitoring_utils.set_custom_attribute('session_inactivity.activity_seen', current_time)
if not last_save or (
datetime.fromisoformat(last_save) + timedelta(seconds=frequency_time_in_seconds) < datetime.utcnow()
Comment thread
robrap marked this conversation as resolved.
Outdated
):
# Allow a full session save periodically
TieredCache.set_all_tiers(LAST_SESSION_SAVE_TIME_KEYNAME, current_time, frequency_time_in_seconds)
Comment thread
robrap marked this conversation as resolved.
Outdated
# .. custom_attribute_name: session_inactivity.session_extended
# .. custom_attribute_description: Marks when sessions are extended through the periodic save.
monitoring_utils.set_custom_attribute('session_inactivity.session_extended', True)
request.session[LAST_TOUCH_KEYNAME] = utc_now.isoformat()
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
"""
Tests for session inactivity timeout middleware.
"""
Loading