~ubuntu-branches/ubuntu/quantal/python-django/quantal-security

« back to all changes in this revision

Viewing changes to django/contrib/auth/management/commands/changepassword.py

  • Committer: Bazaar Package Importer
  • Author(s): Chris Lamb
  • Date: 2010-05-21 07:52:55 UTC
  • mfrom: (1.3.6 upstream)
  • mto: This revision was merged to the branch mainline in revision 28.
  • Revision ID: james.westby@ubuntu.com-20100521075255-ii78v1dyfmyu3uzx
Tags: upstream-1.2
ImportĀ upstreamĀ versionĀ 1.2

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
from django.core.management.base import BaseCommand, CommandError
 
2
from django.contrib.auth.models import User
 
3
import getpass
 
4
 
 
5
class Command(BaseCommand):
 
6
    help = "Change a user's password for django.contrib.auth."
 
7
 
 
8
    requires_model_validation = False
 
9
 
 
10
    def _get_pass(self, prompt="Password: "):
 
11
        p = getpass.getpass(prompt=prompt)
 
12
        if not p:
 
13
            raise CommandError("aborted")
 
14
        return p
 
15
 
 
16
    def handle(self, *args, **options):
 
17
        if len(args) > 1:
 
18
            raise CommandError("need exactly one or zero arguments for username")
 
19
 
 
20
        if args:
 
21
            username, = args
 
22
        else:
 
23
            username = getpass.getuser()
 
24
 
 
25
        try:
 
26
            u = User.objects.get(username=username)
 
27
        except User.DoesNotExist:
 
28
            raise CommandError("user '%s' does not exist" % username)
 
29
 
 
30
        print "Changing password for user '%s'" % u.username
 
31
 
 
32
        MAX_TRIES = 3
 
33
        count = 0
 
34
        p1, p2 = 1, 2  # To make them initially mismatch.
 
35
        while p1 != p2 and count < MAX_TRIES:
 
36
            p1 = self._get_pass()
 
37
            p2 = self._get_pass("Password (again): ")
 
38
            if p1 != p2:
 
39
                print "Passwords do not match. Please try again."
 
40
                count = count + 1
 
41
 
 
42
        if count == MAX_TRIES:
 
43
            raise CommandError("Aborting password change for user '%s' after %s attempts" % (username, count))
 
44
 
 
45
        u.set_password(p1)
 
46
        u.save()
 
47
 
 
48
        return "Password changed successfully for user '%s'" % u.username