sources/saml: Implement MonitoredTask
This commit is contained in:
parent
e4f45eba0a
commit
4ac87d8739
|
@ -3,6 +3,7 @@ from django.utils.timezone import now
|
||||||
from structlog import get_logger
|
from structlog import get_logger
|
||||||
|
|
||||||
from passbook.core.models import User
|
from passbook.core.models import User
|
||||||
|
from passbook.lib.tasks import MonitoredTask, TaskResult, TaskResultStatus
|
||||||
from passbook.lib.utils.time import timedelta_from_string
|
from passbook.lib.utils.time import timedelta_from_string
|
||||||
from passbook.root.celery import CELERY_APP
|
from passbook.root.celery import CELERY_APP
|
||||||
from passbook.sources.saml.models import SAMLSource
|
from passbook.sources.saml.models import SAMLSource
|
||||||
|
@ -10,10 +11,12 @@ from passbook.sources.saml.models import SAMLSource
|
||||||
LOGGER = get_logger()
|
LOGGER = get_logger()
|
||||||
|
|
||||||
|
|
||||||
@CELERY_APP.task()
|
@CELERY_APP.task(bind=True, base=MonitoredTask)
|
||||||
def clean_temporary_users():
|
def clean_temporary_users(self: MonitoredTask):
|
||||||
"""Remove old temporary users"""
|
"""Remove old temporary users"""
|
||||||
_now = now()
|
_now = now()
|
||||||
|
messages = []
|
||||||
|
deleted_users = 0
|
||||||
for user in User.objects.filter(attributes__saml__isnull=False):
|
for user in User.objects.filter(attributes__saml__isnull=False):
|
||||||
sources = SAMLSource.objects.filter(
|
sources = SAMLSource.objects.filter(
|
||||||
pk=user.attributes.get("saml", {}).get("source", "")
|
pk=user.attributes.get("saml", {}).get("source", "")
|
||||||
|
@ -22,6 +25,10 @@ def clean_temporary_users():
|
||||||
LOGGER.warning(
|
LOGGER.warning(
|
||||||
"User has an invalid SAML Source and won't be deleted!", user=user
|
"User has an invalid SAML Source and won't be deleted!", user=user
|
||||||
)
|
)
|
||||||
|
messages.append(
|
||||||
|
f"User {user} has an invalid SAML Source and won't be deleted!"
|
||||||
|
)
|
||||||
|
continue
|
||||||
source = sources.first()
|
source = sources.first()
|
||||||
source_delta = timedelta_from_string(source.temporary_user_delete_after)
|
source_delta = timedelta_from_string(source.temporary_user_delete_after)
|
||||||
if _now - user.last_login >= source_delta:
|
if _now - user.last_login >= source_delta:
|
||||||
|
@ -30,3 +37,6 @@ def clean_temporary_users():
|
||||||
)
|
)
|
||||||
# TODO: Check if user is signed in anywhere?
|
# TODO: Check if user is signed in anywhere?
|
||||||
user.delete()
|
user.delete()
|
||||||
|
deleted_users += 1
|
||||||
|
messages.append(f"Successfully deleted {deleted_users} users.")
|
||||||
|
self.set_status(TaskResult(TaskResultStatus.SUCCESSFUL, messages))
|
||||||
|
|
Reference in New Issue