From 61545d1b8d39c2e60dfdc1b6c608dafa027d7d67 Mon Sep 17 00:00:00 2001 From: Sunil Mohan Adapa Date: Thu, 20 Feb 2020 17:35:16 -0800 Subject: [PATCH] web_framework: Cleanup expired sessions every week Currently, sessions are created as files in /var/lib/plinth/sessions. If a user does not logout, the sessions remains there ever after expiry. Cleanup these accumulating files by running a cleanup job every week. Adding django.contrib.sessions to apps list necessary to ensure that 'clearsessions' management command is available. This creates an empty database table for session storage but is harmless. Tests performed: - When run with the change for first time, migration is run for django.contrib.sessions app. - Change the scheduled interval to 30 seconds in the code. Login as a user. A new session file is created in data/var/lib/plinth/sessions. Forward the system clock by at least 2 weeks. The session expires. Within 30 seconds the file is also removed. - Login, then remove the django-secret.key. In 30 seconds we see a message that the session data is corrupt. Advance the clock by at least 2 weeks. The session file is removed and the message about session data is no longer printed. - Repeat for system level plinth after `./setup.py install` and `sudo -u plinth plinth`. Signed-off-by: Sunil Mohan Adapa Reviewed-by: James Valleroy --- plinth/settings.py | 1 + plinth/web_framework.py | 11 ++++++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/plinth/settings.py b/plinth/settings.py index 1ee546f73..effb75744 100644 --- a/plinth/settings.py +++ b/plinth/settings.py @@ -86,6 +86,7 @@ INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', + 'django.contrib.sessions', 'stronghold', 'plinth', ] diff --git a/plinth/web_framework.py b/plinth/web_framework.py index 2477185b0..80eb5ec26 100644 --- a/plinth/web_framework.py +++ b/plinth/web_framework.py @@ -15,7 +15,7 @@ import django.core.wsgi from django.conf import global_settings from django.contrib.messages import constants as message_constants -from . import cfg, log, module_loader, settings +from . import cfg, glib, log, module_loader, settings logger = logging.getLogger(__name__) @@ -59,6 +59,9 @@ def init(): interactive=False, verbosity=verbosity) os.chmod(cfg.store_file, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP) + # Cleanup expired sessions every day + glib.schedule(24 * 3600, _cleanup_expired_sessions, in_thread=True) + def _get_secret_key(): """Retrieve or create a new Django secret key.""" @@ -105,6 +108,12 @@ def get_languages(): ]) +def _cleanup_expired_sessions(data): + """Cleanup expired Django sessions.""" + verbosity = 1 if cfg.develop else 0 + django.core.management.call_command('clearsessions', verbosity=verbosity) + + def get_wsgi_application(): """Return Django wsgi application.""" return django.core.wsgi.get_wsgi_application()