2019-10-11 11:43:35 +00:00
|
|
|
"""LDAP Sync tasks"""
|
2020-09-19 13:25:17 +00:00
|
|
|
from time import time
|
|
|
|
|
|
|
|
from django.core.cache import cache
|
2020-10-16 19:31:12 +00:00
|
|
|
from django.utils.text import slugify
|
2020-10-16 12:17:47 +00:00
|
|
|
from ldap3.core.exceptions import LDAPException
|
2020-09-19 13:25:17 +00:00
|
|
|
|
2020-10-16 12:17:47 +00:00
|
|
|
from passbook.lib.tasks import MonitoredTask, TaskResult, TaskResultStatus
|
2019-10-11 10:53:48 +00:00
|
|
|
from passbook.root.celery import CELERY_APP
|
|
|
|
from passbook.sources.ldap.models import LDAPSource
|
2020-09-21 19:35:50 +00:00
|
|
|
from passbook.sources.ldap.sync import LDAPSynchronizer
|
2019-10-11 10:53:48 +00:00
|
|
|
|
|
|
|
|
|
|
|
@CELERY_APP.task()
|
2020-10-16 12:17:47 +00:00
|
|
|
def ldap_sync_all():
|
2019-10-11 10:53:48 +00:00
|
|
|
"""Sync all sources"""
|
|
|
|
for source in LDAPSource.objects.filter(enabled=True):
|
2020-10-16 12:17:47 +00:00
|
|
|
ldap_sync.delay(source.pk)
|
2020-09-14 21:35:01 +00:00
|
|
|
|
|
|
|
|
2020-10-16 12:17:47 +00:00
|
|
|
@CELERY_APP.task(bind=True, base=MonitoredTask)
|
|
|
|
def ldap_sync(self: MonitoredTask, source_pk: int):
|
2020-10-19 19:35:31 +00:00
|
|
|
"""Synchronization of an LDAP Source"""
|
2020-09-19 13:25:17 +00:00
|
|
|
source: LDAPSource = LDAPSource.objects.get(pk=source_pk)
|
2020-10-19 19:30:21 +00:00
|
|
|
self.set_uid(slugify(source.name))
|
2020-10-16 12:17:47 +00:00
|
|
|
try:
|
|
|
|
syncer = LDAPSynchronizer(source)
|
|
|
|
user_count = syncer.sync_users()
|
|
|
|
group_count = syncer.sync_groups()
|
|
|
|
syncer.sync_membership()
|
|
|
|
cache_key = source.state_cache_prefix("last_sync")
|
|
|
|
cache.set(cache_key, time(), timeout=60 * 60)
|
|
|
|
self.set_status(
|
|
|
|
TaskResult(
|
|
|
|
TaskResultStatus.SUCCESSFUL,
|
|
|
|
[f"Synced {user_count} users", f"Synced {group_count} groups"],
|
|
|
|
)
|
|
|
|
)
|
|
|
|
except LDAPException as exc:
|
2020-10-19 19:30:21 +00:00
|
|
|
self.set_status(TaskResult(TaskResultStatus.ERROR).with_error(exc))
|