web/lib/django/contrib/auth/management/commands/createsuperuser.py
changeset 38 77b6da96e6f1
equal deleted inserted replaced
37:8d941af65caf 38:77b6da96e6f1
       
     1 """
       
     2 Management utility to create superusers.
       
     3 """
       
     4 
       
     5 import getpass
       
     6 import os
       
     7 import re
       
     8 import sys
       
     9 from optparse import make_option
       
    10 from django.contrib.auth.models import User
       
    11 from django.core import exceptions
       
    12 from django.core.management.base import BaseCommand, CommandError
       
    13 from django.utils.translation import ugettext as _
       
    14 
       
    15 RE_VALID_USERNAME = re.compile('[\w.@+-]+$')
       
    16 
       
    17 EMAIL_RE = re.compile(
       
    18     r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*"  # dot-atom
       
    19     r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"' # quoted-string
       
    20     r')@(?:[A-Z0-9-]+\.)+[A-Z]{2,6}$', re.IGNORECASE)  # domain
       
    21 
       
    22 def is_valid_email(value):
       
    23     if not EMAIL_RE.search(value):
       
    24         raise exceptions.ValidationError(_('Enter a valid e-mail address.'))
       
    25 
       
    26 class Command(BaseCommand):
       
    27     option_list = BaseCommand.option_list + (
       
    28         make_option('--username', dest='username', default=None,
       
    29             help='Specifies the username for the superuser.'),
       
    30         make_option('--email', dest='email', default=None,
       
    31             help='Specifies the email address for the superuser.'),
       
    32         make_option('--noinput', action='store_false', dest='interactive', default=True,
       
    33             help='Tells Django to NOT prompt the user for input of any kind. '    \
       
    34                  'You must use --username and --email with --noinput, and '      \
       
    35                  'superusers created with --noinput will not be able to log in '  \
       
    36                  'until they\'re given a valid password.'),
       
    37     )
       
    38     help = 'Used to create a superuser.'
       
    39 
       
    40     def handle(self, *args, **options):
       
    41         username = options.get('username', None)
       
    42         email = options.get('email', None)
       
    43         interactive = options.get('interactive')
       
    44         
       
    45         # Do quick and dirty validation if --noinput
       
    46         if not interactive:
       
    47             if not username or not email:
       
    48                 raise CommandError("You must use --username and --email with --noinput.")
       
    49             if not RE_VALID_USERNAME.match(username):
       
    50                 raise CommandError("Invalid username. Use only letters, digits, and underscores")
       
    51             try:
       
    52                 is_valid_email(email)
       
    53             except exceptions.ValidationError:
       
    54                 raise CommandError("Invalid email address.")
       
    55 
       
    56         password = ''
       
    57 
       
    58         # Try to determine the current system user's username to use as a default.
       
    59         try:
       
    60             import pwd
       
    61             default_username = pwd.getpwuid(os.getuid())[0].replace(' ', '').lower()
       
    62         except (ImportError, KeyError):
       
    63             # KeyError will be raised by getpwuid() if there is no
       
    64             # corresponding entry in the /etc/passwd file (a very restricted
       
    65             # chroot environment, for example).
       
    66             default_username = ''
       
    67 
       
    68         # Determine whether the default username is taken, so we don't display
       
    69         # it as an option.
       
    70         if default_username:
       
    71             try:
       
    72                 User.objects.get(username=default_username)
       
    73             except User.DoesNotExist:
       
    74                 pass
       
    75             else:
       
    76                 default_username = ''
       
    77 
       
    78         # Prompt for username/email/password. Enclose this whole thing in a
       
    79         # try/except to trap for a keyboard interrupt and exit gracefully.
       
    80         if interactive:
       
    81             try:
       
    82             
       
    83                 # Get a username
       
    84                 while 1:
       
    85                     if not username:
       
    86                         input_msg = 'Username'
       
    87                         if default_username:
       
    88                             input_msg += ' (Leave blank to use %r)' % default_username
       
    89                         username = raw_input(input_msg + ': ')
       
    90                     if default_username and username == '':
       
    91                         username = default_username
       
    92                     if not RE_VALID_USERNAME.match(username):
       
    93                         sys.stderr.write("Error: That username is invalid. Use only letters, digits and underscores.\n")
       
    94                         username = None
       
    95                         continue
       
    96                     try:
       
    97                         User.objects.get(username=username)
       
    98                     except User.DoesNotExist:
       
    99                         break
       
   100                     else:
       
   101                         sys.stderr.write("Error: That username is already taken.\n")
       
   102                         username = None
       
   103             
       
   104                 # Get an email
       
   105                 while 1:
       
   106                     if not email:
       
   107                         email = raw_input('E-mail address: ')
       
   108                     try:
       
   109                         is_valid_email(email)
       
   110                     except exceptions.ValidationError:
       
   111                         sys.stderr.write("Error: That e-mail address is invalid.\n")
       
   112                         email = None
       
   113                     else:
       
   114                         break
       
   115             
       
   116                 # Get a password
       
   117                 while 1:
       
   118                     if not password:
       
   119                         password = getpass.getpass()
       
   120                         password2 = getpass.getpass('Password (again): ')
       
   121                         if password != password2:
       
   122                             sys.stderr.write("Error: Your passwords didn't match.\n")
       
   123                             password = None
       
   124                             continue
       
   125                     if password.strip() == '':
       
   126                         sys.stderr.write("Error: Blank passwords aren't allowed.\n")
       
   127                         password = None
       
   128                         continue
       
   129                     break
       
   130             except KeyboardInterrupt:
       
   131                 sys.stderr.write("\nOperation cancelled.\n")
       
   132                 sys.exit(1)
       
   133         
       
   134         User.objects.create_superuser(username, email, password)
       
   135         print "Superuser created successfully."