regenerate_ldap_members.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 coin.members.models import Member, LdapUser
  6. class Command(BaseCommand):
  7. args = '[login1 login2 ...]'
  8. help = """Regenerate user objects in the LDAP backend. This is useful if you
  9. have added or modified an LDAP attribute and want to apply the change
  10. to all existing members. By default, all members from the local
  11. database are regenerated this way, but you can restrict the query by
  12. passing a list of user logins as argument.
  13. If --erase-all is passed, then the LDAP database is cleared of all its
  14. users before regenerating users from the local database. Use this
  15. option with caution, as you will lose any user that was present in the
  16. LDAP database but not in the local database."""
  17. option_list = BaseCommand.option_list + (
  18. make_option('--erase-all',
  19. action='store_true',
  20. dest='erase',
  21. default=False,
  22. help='Erase all LDAP users before proceeding with the regeneration'),
  23. )
  24. def handle(self, *args, **options):
  25. if len(args) == 0:
  26. members = Member.objects.all()
  27. else:
  28. members = Member.objects.filter(username__in=args)
  29. self.stdout.write("Regeneration of {count} members.".format(
  30. count=len(members)))
  31. # Delete every user is asked to do so
  32. if options['erase']:
  33. self.stdout.write("First erasing all existing LDAP users...")
  34. LdapUser.objects.all().delete()
  35. # Regenerate users
  36. for m in members:
  37. login = m.username
  38. if options['verbosity'] >= 2:
  39. self.stdout.write("Regenerating user {login}...".format(login=login))
  40. # Try deleting the LDAP user first, so that we can recreate it
  41. try:
  42. LdapUser.objects.get(pk=login).delete()
  43. except LdapUser.DoesNotExist:
  44. pass
  45. # Create the LDAP user
  46. m.sync_to_ldap(creation=True, update_fields=None)
  47. self.stdout.write("Done")