2020-06-24 20:27:14 +00:00
|
|
|
"""passbook saml source tasks"""
|
|
|
|
from django.utils.timezone import now
|
|
|
|
from structlog import get_logger
|
|
|
|
|
|
|
|
from passbook.core.models import User
|
2020-10-16 12:30:44 +00:00
|
|
|
from passbook.lib.tasks import MonitoredTask, TaskResult, TaskResultStatus
|
2020-07-20 09:35:16 +00:00
|
|
|
from passbook.lib.utils.time import timedelta_from_string
|
2020-06-24 20:27:14 +00:00
|
|
|
from passbook.root.celery import CELERY_APP
|
|
|
|
from passbook.sources.saml.models import SAMLSource
|
|
|
|
|
|
|
|
LOGGER = get_logger()
|
|
|
|
|
|
|
|
|
2020-10-16 12:30:44 +00:00
|
|
|
@CELERY_APP.task(bind=True, base=MonitoredTask)
|
|
|
|
def clean_temporary_users(self: MonitoredTask):
|
2020-10-19 19:35:31 +00:00
|
|
|
"""Remove temporary users created by SAML Sources"""
|
2020-06-24 20:27:14 +00:00
|
|
|
_now = now()
|
2020-10-16 12:30:44 +00:00
|
|
|
messages = []
|
|
|
|
deleted_users = 0
|
2020-06-24 20:27:14 +00:00
|
|
|
for user in User.objects.filter(attributes__saml__isnull=False):
|
|
|
|
sources = SAMLSource.objects.filter(
|
|
|
|
pk=user.attributes.get("saml", {}).get("source", "")
|
|
|
|
)
|
|
|
|
if not sources.exists():
|
|
|
|
LOGGER.warning(
|
|
|
|
"User has an invalid SAML Source and won't be deleted!", user=user
|
|
|
|
)
|
2020-10-16 12:30:44 +00:00
|
|
|
messages.append(
|
|
|
|
f"User {user} has an invalid SAML Source and won't be deleted!"
|
|
|
|
)
|
|
|
|
continue
|
2020-06-24 20:27:14 +00:00
|
|
|
source = sources.first()
|
|
|
|
source_delta = timedelta_from_string(source.temporary_user_delete_after)
|
|
|
|
if _now - user.last_login >= source_delta:
|
|
|
|
LOGGER.debug(
|
|
|
|
"User is expired and will be deleted.", user=user, delta=source_delta
|
|
|
|
)
|
2020-06-24 20:46:20 +00:00
|
|
|
# TODO: Check if user is signed in anywhere?
|
2020-06-24 20:27:14 +00:00
|
|
|
user.delete()
|
2020-10-16 12:30:44 +00:00
|
|
|
deleted_users += 1
|
|
|
|
messages.append(f"Successfully deleted {deleted_users} users.")
|
|
|
|
self.set_status(TaskResult(TaskResultStatus.SUCCESSFUL, messages))
|