changepassword.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. from __future__ import unicode_literals
  2. import getpass
  3. from optparse import make_option
  4. from django.contrib.auth import get_user_model
  5. from django.core.management.base import BaseCommand, CommandError
  6. from django.db import DEFAULT_DB_ALIAS
  7. from django.utils.encoding import force_str
  8. class Command(BaseCommand):
  9. option_list = BaseCommand.option_list + (
  10. make_option('--database', action='store', dest='database',
  11. default=DEFAULT_DB_ALIAS, help='Specifies the database to use. Default is "default".'),
  12. )
  13. help = "Change a user's password for django.contrib.auth."
  14. requires_system_checks = False
  15. def _get_pass(self, prompt="Password: "):
  16. p = getpass.getpass(prompt=force_str(prompt))
  17. if not p:
  18. raise CommandError("aborted")
  19. return p
  20. def handle(self, *args, **options):
  21. if len(args) > 1:
  22. raise CommandError("need exactly one or zero arguments for username")
  23. if args:
  24. username, = args
  25. else:
  26. username = getpass.getuser()
  27. UserModel = get_user_model()
  28. try:
  29. u = UserModel._default_manager.using(options.get('database')).get(**{
  30. UserModel.USERNAME_FIELD: username
  31. })
  32. except UserModel.DoesNotExist:
  33. raise CommandError("user '%s' does not exist" % username)
  34. self.stdout.write("Changing password for user '%s'\n" % u)
  35. MAX_TRIES = 3
  36. count = 0
  37. p1, p2 = 1, 2 # To make them initially mismatch.
  38. while p1 != p2 and count < MAX_TRIES:
  39. p1 = self._get_pass()
  40. p2 = self._get_pass("Password (again): ")
  41. if p1 != p2:
  42. self.stdout.write("Passwords do not match. Please try again.\n")
  43. count = count + 1
  44. if count == MAX_TRIES:
  45. raise CommandError("Aborting password change for user '%s' after %s attempts" % (u, count))
  46. u.set_password(p1)
  47. u.save()
  48. return "Password changed successfully for user '%s'" % u