| 1 |
import getpass |
| 2 |
|
| 3 |
from django.contrib.auth import get_user_model |
| 4 |
from django.contrib.auth.password_validation import validate_password |
| 5 |
from django.core.exceptions import ValidationError |
| 6 |
from django.core.management.base import BaseCommand, CommandError |
| 7 |
from django.db import DEFAULT_DB_ALIAS, connections |
| 8 |
|
| 9 |
UserModel = get_user_model() |
| 10 |
|
| 11 |
|
| 12 |
class Command(BaseCommand): |
| 13 |
help = "Change a user's password for django.contrib.auth." |
| 14 |
requires_migrations_checks = True |
| 15 |
requires_system_checks = [] |
| 16 |
|
| 17 |
def _get_pass(self, prompt="Password: "): |
| 18 |
p = getpass.getpass(prompt=prompt) |
| 19 |
if not p: |
| 20 |
raise CommandError("aborted") |
| 21 |
return p |
| 22 |
|
| 23 |
def add_arguments(self, parser): |
| 24 |
parser.add_argument( |
| 25 |
"username", |
| 26 |
nargs="?", |
| 27 |
help=( |
| 28 |
"Username to change password for; by default, it's the current " |
| 29 |
"username." |
| 30 |
), |
| 31 |
) |
| 32 |
parser.add_argument( |
| 33 |
"--database", |
| 34 |
default=DEFAULT_DB_ALIAS, |
| 35 |
choices=tuple(connections), |
| 36 |
help='Specifies the database to use. Default is "default".', |
| 37 |
) |
| 38 |
|
| 39 |
def handle(self, *args, **options): |
| 40 |
if options["username"]: |
| 41 |
username = options["username"] |
| 42 |
else: |
| 43 |
username = getpass.getuser() |
| 44 |
|
| 45 |
try: |
| 46 |
u = UserModel._default_manager.using(options["database"]).get( |
| 47 |
**{UserModel.USERNAME_FIELD: username} |
| 48 |
) |
| 49 |
except UserModel.DoesNotExist: |
| 50 |
raise CommandError("user '%s' does not exist" % username) |
| 51 |
|
| 52 |
self.stdout.write("Changing password for user '%s'" % u) |
| 53 |
|
| 54 |
MAX_TRIES = 3 |
| 55 |
count = 0 |
| 56 |
p1, p2 = 1, 2 # To make them initially mismatch. |
| 57 |
password_validated = False |
| 58 |
while (p1 != p2 or not password_validated) and count < MAX_TRIES: |
| 59 |
p1 = self._get_pass() |
| 60 |
p2 = self._get_pass("Password (again): ") |
| 61 |
if p1 != p2: |
| 62 |
self.stdout.write("Passwords do not match. Please try again.") |
| 63 |
count += 1 |
| 64 |
# Don't validate passwords that don't match. |
| 65 |
continue |
| 66 |
try: |
| 67 |
validate_password(p2, u) |
| 68 |
except ValidationError as err: |
| 69 |
self.stderr.write("\n".join(err.messages)) |
| 70 |
count += 1 |
| 71 |
else: |
| 72 |
password_validated = True |
| 73 |
|
| 74 |
if count == MAX_TRIES: |
| 75 |
raise CommandError( |
| 76 |
"Aborting password change for user '%s' after %s attempts" % (u, count) |
| 77 |
) |
| 78 |
|
| 79 |
u.set_password(p1) |
| 80 |
u.save() |
| 81 |
|
| 82 |
return "Password changed successfully for user '%s'" % u |