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