From f0415640d57c7a63ce1dbb1126d28aa06d221f8a Mon Sep 17 00:00:00 2001 From: Oliver Date: Thu, 19 Aug 2021 16:34:57 +1000 Subject: [PATCH] Run periodic (daily) task to clear out expired sessions --- InvenTree/InvenTree/apps.py | 10 ++++++++++ InvenTree/InvenTree/tasks.py | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/InvenTree/InvenTree/apps.py b/InvenTree/InvenTree/apps.py index feb46ee667..ee86b975dc 100644 --- a/InvenTree/InvenTree/apps.py +++ b/InvenTree/InvenTree/apps.py @@ -32,27 +32,37 @@ class InvenTreeConfig(AppConfig): logger.info("Starting background tasks...") + # Remove successful task results from the database InvenTree.tasks.schedule_task( 'InvenTree.tasks.delete_successful_tasks', schedule_type=Schedule.DAILY, ) + # Check for InvenTree updates InvenTree.tasks.schedule_task( 'InvenTree.tasks.check_for_updates', schedule_type=Schedule.DAILY ) + # Heartbeat to let the server know the background worker is running InvenTree.tasks.schedule_task( 'InvenTree.tasks.heartbeat', schedule_type=Schedule.MINUTES, minutes=15 ) + # Keep exchange rates up to date InvenTree.tasks.schedule_task( 'InvenTree.tasks.update_exchange_rates', schedule_type=Schedule.DAILY, ) + # Remove expired sessions + InvenTree.tasks.schedule_task( + 'InvenTree.tasks.delete_expired_sessions', + schedule_type=Schedule.DAILY, + ) + def update_exchange_rates(self): """ Update exchange rates each time the server is started, *if*: diff --git a/InvenTree/InvenTree/tasks.py b/InvenTree/InvenTree/tasks.py index deb834c322..5fb6960601 100644 --- a/InvenTree/InvenTree/tasks.py +++ b/InvenTree/InvenTree/tasks.py @@ -204,6 +204,25 @@ def check_for_updates(): ) +def delete_expired_sessions(): + """ + Remove any expired user sessions from the database + """ + + try: + from django.contrib.sessions.models import Session + + # Delete any sessions that expired more than a day ago + expired = Session.objects.filter(expire_date__lt=timezone.now() - timedelta(days=1)) + + if True or expired.count() > 0: + logger.info(f"Deleting {expired.count()} expired sessions.") + expired.delete() + + except AppRegistryNotReady: + logger.info("Could not perform 'delete_expired_sessions' - App registry not ready") + + def update_exchange_rates(): """ Update currency exchange rates