Code

Ticket #6273: 6273_change_password_auth_command.diff

File 6273_change_password_auth_command.diff, 2.3 KB (added by justinlilly, 5 years ago)

Now with docs and renamed to change_password

Line 
1diff --git a/django/contrib/auth/management/commands/change_password.py b/django/contrib/auth/management/commands/change_password.py
2new file mode 100644
3index 0000000..34c7b04
4--- /dev/null
5+++ b/django/contrib/auth/management/commands/change_password.py
6@@ -0,0 +1,41 @@
7+from django.core.management.base import BaseCommand, CommandError
8+from django.contrib.auth.models import User
9+import getpass
10+
11+class Command(BaseCommand):
12+    help = "Change a user's password for django.contrib.auth."
13+
14+    requires_model_validation = False
15+
16+    def _get_pass(self, prompt="Password: "):
17+        p = getpass.getpass(prompt=prompt)
18+        if not p:
19+            raise CommandError("aborted")
20+        return p
21+
22+    def handle(self, *args, **options):
23+        if len(args) > 1:
24+            raise CommandError("need exactly one or zero arguments for username")
25+
26+        if args:
27+            username, = args
28+        else:
29+            username = getpass.getuser()
30+
31+        try:
32+            u = User.objects.get(username=username)
33+        except User.DoesNotExist:
34+            raise CommandError("user %s does not exist" % username)
35+
36+        print "Changing password for user", u.username
37+        p1, p2 = 1, 2  # To make them mismatch.
38+        while p1 != p2:
39+            p1 = self._get_pass()
40+            p2 = self._get_pass("Password (again): ")
41+            if p1 != p2:
42+                print "Passwords do not match, try again"
43+
44+        u.set_password(p1)
45+        u.save()
46+
47+        return "Password changed successfully for user " + u.username
48diff --git a/docs/topics/auth.txt b/docs/topics/auth.txt
49index 7858e44..f4c046b 100644
50--- a/docs/topics/auth.txt
51+++ b/docs/topics/auth.txt
52@@ -330,6 +330,16 @@ Don't set the :attr:`~django.contrib.auth.models.User.password` attribute
53 directly unless you know what you're doing. This is explained in the next
54 section.
55 
56+.. versionadded:: 1.2
57+   The ``manage.py change_password`` command is new.
58+
59+:djadmin:`manage.py change_password <username>` offers a method of
60+changing a User's password from the command line. It prompts you to
61+change the password of a given user which you must enter twice. If
62+they both match, the new password will be changed immediately. If you
63+do not supply a user, the command will attempt to change the password
64+whose username matches the current user.
65+
66 Passwords
67 ---------
68