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 <sunil@medhas.org>
Reviewed-by: James Valleroy <jvalleroy@mailbox.org>
This commit is contained in:
Sunil Mohan Adapa 2020-02-20 17:35:16 -08:00 committed by James Valleroy
parent fd345aca80
commit 61545d1b8d
No known key found for this signature in database
GPG Key ID: 77C0C75E7B650808
2 changed files with 11 additions and 1 deletions

View File

@ -86,6 +86,7 @@ INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.messages',
'django.contrib.sessions',
'stronghold',
'plinth',
]

View File

@ -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()