2019-11-11 08:41:32 +00:00
|
|
|
# coding: utf-8
|
2023-04-03 08:45:59 +00:00
|
|
|
#
|
2023-02-19 09:57:48 +00:00
|
|
|
from celery import shared_task
|
|
|
|
from django.conf import settings
|
|
|
|
from django.utils.translation import ugettext_lazy as _
|
2023-04-03 08:45:59 +00:00
|
|
|
from django.db import transaction
|
2019-11-11 08:41:32 +00:00
|
|
|
|
|
|
|
from common.utils import get_logger
|
2023-02-19 09:57:48 +00:00
|
|
|
from ops.celery.decorator import after_app_ready_start
|
|
|
|
from ops.celery.utils import (
|
|
|
|
create_or_update_celery_periodic_tasks, disable_celery_periodic_task
|
|
|
|
)
|
|
|
|
from orgs.models import Organization
|
|
|
|
from ..utils import LDAPSyncUtil, LDAPServerUtil, LDAPImportUtil
|
2019-11-11 08:41:32 +00:00
|
|
|
|
2023-02-19 09:57:48 +00:00
|
|
|
__all__ = ['sync_ldap_user', 'import_ldap_user_periodic', 'import_ldap_user']
|
2019-11-11 08:41:32 +00:00
|
|
|
|
|
|
|
logger = get_logger(__file__)
|
|
|
|
|
|
|
|
|
2020-09-07 12:33:44 +00:00
|
|
|
def sync_ldap_user():
|
2019-11-11 08:41:32 +00:00
|
|
|
LDAPSyncUtil().perform_sync()
|
2023-02-19 09:57:48 +00:00
|
|
|
|
|
|
|
|
|
|
|
@shared_task(verbose_name=_('Import ldap user'))
|
2023-04-03 08:45:59 +00:00
|
|
|
@transaction.atomic
|
2023-02-19 09:57:48 +00:00
|
|
|
def import_ldap_user():
|
|
|
|
logger.info("Start import ldap user task")
|
|
|
|
util_server = LDAPServerUtil()
|
|
|
|
util_import = LDAPImportUtil()
|
|
|
|
users = util_server.search()
|
|
|
|
if settings.XPACK_ENABLED:
|
|
|
|
org_id = settings.AUTH_LDAP_SYNC_ORG_ID
|
|
|
|
default_org = None
|
|
|
|
else:
|
|
|
|
# 社区版默认导入Default组织
|
|
|
|
org_id = Organization.DEFAULT_ID
|
|
|
|
default_org = Organization.default()
|
|
|
|
org = Organization.get_instance(org_id, default=default_org)
|
|
|
|
errors = util_import.perform_import(users, org)
|
|
|
|
if errors:
|
|
|
|
logger.error("Imported LDAP users errors: {}".format(errors))
|
|
|
|
else:
|
|
|
|
logger.info('Imported {} users successfully'.format(len(users)))
|
|
|
|
|
|
|
|
|
|
|
|
@shared_task(verbose_name=_('Periodic import ldap user'))
|
|
|
|
@after_app_ready_start
|
|
|
|
def import_ldap_user_periodic():
|
|
|
|
if not settings.AUTH_LDAP:
|
|
|
|
return
|
|
|
|
task_name = 'import_ldap_user_periodic'
|
|
|
|
disable_celery_periodic_task(task_name)
|
|
|
|
if not settings.AUTH_LDAP_SYNC_IS_PERIODIC:
|
|
|
|
return
|
|
|
|
|
|
|
|
interval = settings.AUTH_LDAP_SYNC_INTERVAL
|
|
|
|
if isinstance(interval, int):
|
|
|
|
interval = interval * 3600
|
|
|
|
else:
|
|
|
|
interval = None
|
|
|
|
crontab = settings.AUTH_LDAP_SYNC_CRONTAB
|
|
|
|
if crontab:
|
|
|
|
# 优先使用 crontab
|
|
|
|
interval = None
|
|
|
|
tasks = {
|
|
|
|
task_name: {
|
|
|
|
'task': import_ldap_user.name,
|
|
|
|
'interval': interval,
|
|
|
|
'crontab': crontab,
|
|
|
|
'enabled': True,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
create_or_update_celery_periodic_tasks(tasks)
|