regenerate_ldap_members.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. from optparse import make_option
  4. from django.core.management.base import BaseCommand, CommandError
  5. from django.conf import settings
  6. from coin.members.models import Member, LdapUser
  7. class Command(BaseCommand):
  8. args = '[login1 login2 ...]'
  9. help = """Regenerate user objects in the LDAP backend. This is useful if you
  10. have added or modified an LDAP attribute and want to apply the change
  11. to all existing members. By default, all members from the local
  12. database are regenerated this way, but you can restrict the query by
  13. passing a list of user logins as argument.
  14. If --erase-all is passed, then the LDAP database is cleared of all its
  15. users before regenerating users from the local database. Use this
  16. option with a lot of caution, as you will lose any user that was
  17. present in the LDAP database but not in the local database.
  18. Additionally, Unix UIDs (attribute "uidNumber" in LDAP) are currently
  19. generated when saving a new user, so --erase-all might lead to
  20. different UIDs after the regeneration. This is certainly a bad idea
  21. if your Unix users are based on LDAP."""
  22. option_list = BaseCommand.option_list + (
  23. make_option('--erase-all',
  24. action='store_true',
  25. dest='erase',
  26. default=False,
  27. help='Erase all LDAP users before proceeding with the regeneration'),
  28. )
  29. def handle(self, *args, **options):
  30. if not settings.LDAP_ACTIVATE:
  31. self.stdout.write("LDAP disabled, not doing anything (check LDAP_ACTIVATE in settings.py).")
  32. return
  33. if len(args) == 0:
  34. members = Member.objects.all()
  35. else:
  36. members = Member.objects.filter(username__in=args)
  37. self.stdout.write("Regeneration of {count} members.".format(
  38. count=len(members)))
  39. # Delete every user is asked to do so
  40. if options['erase']:
  41. self.stdout.write("First erasing all existing LDAP users...")
  42. LdapUser.objects.all().delete()
  43. # Regenerate users
  44. for m in members:
  45. login = m.username
  46. if options['verbosity'] >= 2:
  47. self.stdout.write("Regenerating user {login}...".format(login=login))
  48. # The user might not exist in LDAP (maybe it was deleted or something)
  49. try:
  50. LdapUser.objects.get(pk=login)
  51. m.sync_to_ldap(creation=False, update_fields=None)
  52. except LdapUser.DoesNotExist:
  53. # Create the LDAP user
  54. self.stderr.write("WARNING: user {login} not found in LDAP, "
  55. "creating it (look at the resulting Unix "
  56. "uidNumber to see if it's ok).".format(login=login))
  57. m.sync_to_ldap(creation=True, update_fields=None)
  58. self.stdout.write("Done")