2013-11-25 22:22:17 +01:00
|
|
|
|
2017-12-13 01:45:57 +01:00
|
|
|
import logging
|
2019-01-11 11:25:36 +01:00
|
|
|
|
|
|
|
from argparse import ArgumentParser
|
|
|
|
from typing import Any, List
|
|
|
|
|
2013-11-25 22:22:17 +01:00
|
|
|
|
2017-11-16 00:43:27 +01:00
|
|
|
from django.conf import settings
|
2013-11-25 22:22:17 +01:00
|
|
|
from django.db.utils import IntegrityError
|
|
|
|
|
2017-12-13 01:45:57 +01:00
|
|
|
from zerver.lib.logging_util import log_to_file
|
2019-01-11 11:25:36 +01:00
|
|
|
from zerver.lib.management import ZulipBaseCommand
|
2017-11-16 00:43:27 +01:00
|
|
|
from zerver.models import UserProfile
|
2019-01-12 12:32:54 +01:00
|
|
|
from zproject.backends import ZulipLDAPException, sync_user_from_ldap
|
2013-11-25 22:22:17 +01:00
|
|
|
|
|
|
|
## Setup ##
|
2017-12-13 01:45:57 +01:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
log_to_file(logger, settings.LDAP_SYNC_LOG_PATH)
|
2013-11-25 22:22:17 +01:00
|
|
|
|
|
|
|
# Run this on a cronjob to pick up on name changes.
|
2019-01-11 11:25:36 +01:00
|
|
|
def sync_ldap_user_data(user_profiles: List[UserProfile]) -> None:
|
2013-11-25 22:22:17 +01:00
|
|
|
logger.info("Starting update.")
|
2019-01-11 11:25:36 +01:00
|
|
|
for u in user_profiles:
|
2013-11-25 22:22:17 +01:00
|
|
|
# This will save the user if relevant, and will do nothing if the user
|
|
|
|
# does not exist.
|
|
|
|
try:
|
2019-01-12 12:32:54 +01:00
|
|
|
if sync_user_from_ldap(u):
|
2013-11-25 22:22:17 +01:00
|
|
|
logger.info("Updated %s." % (u.email,))
|
|
|
|
else:
|
|
|
|
logger.warning("Did not find %s in LDAP." % (u.email,))
|
2019-01-13 13:53:52 +01:00
|
|
|
if settings.LDAP_DEACTIVATE_NON_MATCHING_USERS:
|
|
|
|
logger.info("Deactivated non-matching user: %s" % (u.email,))
|
2018-08-20 19:30:19 +02:00
|
|
|
except ZulipLDAPException as e:
|
|
|
|
logger.error("Error attempting to update user %s:" % (u.email,))
|
|
|
|
logger.error(e)
|
2013-11-25 22:22:17 +01:00
|
|
|
logger.info("Finished update.")
|
|
|
|
|
2019-01-11 11:25:36 +01:00
|
|
|
class Command(ZulipBaseCommand):
|
|
|
|
def add_arguments(self, parser: ArgumentParser) -> None:
|
|
|
|
self.add_realm_args(parser)
|
|
|
|
self.add_user_list_args(parser)
|
|
|
|
|
2017-10-26 11:35:57 +02:00
|
|
|
def handle(self, *args: Any, **options: Any) -> None:
|
2019-01-11 11:25:36 +01:00
|
|
|
if "realm_id" in options:
|
|
|
|
realm = self.get_realm(options)
|
|
|
|
user_profiles = self.get_users(options, realm, is_bot=False)
|
|
|
|
else:
|
|
|
|
user_profiles = UserProfile.objects.select_related().filter(is_bot=False)
|
|
|
|
sync_ldap_user_data(user_profiles)
|