Ticket #5614: create_superuser.2.diff

File create_superuser.2.diff, 13.4 KB (added by Øyvind Saltvik <oyvind@…>, 17 years ago)

Forgot to svn add init.py

  • django/contrib/auth/management.py

     
    1 """
    2 Creates permissions for all installed apps that need permissions.
    3 """
    4 
    5 from django.dispatch import dispatcher
    6 from django.db.models import get_models, signals
    7 from django.contrib.auth import models as auth_app
    8 
    9 def _get_permission_codename(action, opts):
    10     return u'%s_%s' % (action, opts.object_name.lower())
    11 
    12 def _get_all_permissions(opts):
    13     "Returns (codename, name) for all permissions in the given opts."
    14     perms = []
    15     for action in ('add', 'change', 'delete'):
    16         perms.append((_get_permission_codename(action, opts), u'Can %s %s' % (action, opts.verbose_name_raw)))
    17     return perms + list(opts.permissions)
    18 
    19 def create_permissions(app, created_models, verbosity):
    20     from django.contrib.contenttypes.models import ContentType
    21     from django.contrib.auth.models import Permission
    22     app_models = get_models(app)
    23     if not app_models:
    24         return
    25     for klass in app_models:
    26         ctype = ContentType.objects.get_for_model(klass)
    27         for codename, name in _get_all_permissions(klass._meta):
    28             p, created = Permission.objects.get_or_create(codename=codename, content_type__pk=ctype.id,
    29                 defaults={'name': name, 'content_type': ctype})
    30             if created and verbosity >= 2:
    31                 print "Adding permission '%s'" % p
    32 
    33 def create_superuser(app, created_models, verbosity, **kwargs):
    34     from django.contrib.auth.models import User
    35     from django.contrib.auth.create_superuser import createsuperuser as do_create
    36     if User in created_models and kwargs.get('interactive', True):
    37         msg = "\nYou just installed Django's auth system, which means you don't have " \
    38                 "any superusers defined.\nWould you like to create one now? (yes/no): "
    39         confirm = raw_input(msg)
    40         while 1:
    41             if confirm not in ('yes', 'no'):
    42                 confirm = raw_input('Please enter either "yes" or "no": ')
    43                 continue
    44             if confirm == 'yes':
    45                 do_create()
    46             break
    47 
    48 dispatcher.connect(create_permissions, signal=signals.post_syncdb)
    49 dispatcher.connect(create_superuser, sender=auth_app, signal=signals.post_syncdb)
  • django/contrib/auth/create_superuser.py

     
    1 """
    2 Helper function for creating superusers in the authentication system.
    3 
    4 If run from the command line, this module lets you create a superuser
    5 interactively.
    6 """
    7 
    8 from django.core import validators
    9 from django.contrib.auth.models import User
    10 import getpass
    11 import os
    12 import sys
    13 import re
    14 
    15 RE_VALID_USERNAME = re.compile('\w+$')
    16 
    17 def createsuperuser(username=None, email=None, password=None):
    18     """
    19     Helper function for creating a superuser from the command line. All
    20     arguments are optional and will be prompted-for if invalid or not given.
    21     """
    22     try:
    23         import pwd
    24     except ImportError:
    25         default_username = ''
    26     else:
    27         # Determine the current system user's username, to use as a default.
    28         default_username = pwd.getpwuid(os.getuid())[0].replace(' ', '').lower()
    29 
    30     # Determine whether the default username is taken, so we don't display
    31     # it as an option.
    32     if default_username:
    33         try:
    34             User.objects.get(username=default_username)
    35         except User.DoesNotExist:
    36             pass
    37         else:
    38             default_username = ''
    39 
    40     try:
    41         while 1:
    42             if not username:
    43                 input_msg = 'Username'
    44                 if default_username:
    45                     input_msg += ' (Leave blank to use %r)' % default_username
    46                 username = raw_input(input_msg + ': ')
    47             if default_username and username == '':
    48                 username = default_username
    49             if not RE_VALID_USERNAME.match(username):
    50                 sys.stderr.write("Error: That username is invalid. Use only letters, digits and underscores.\n")
    51                 username = None
    52                 continue
    53             try:
    54                 User.objects.get(username=username)
    55             except User.DoesNotExist:
    56                 break
    57             else:
    58                 sys.stderr.write("Error: That username is already taken.\n")
    59                 username = None
    60         while 1:
    61             if not email:
    62                 email = raw_input('E-mail address: ')
    63             try:
    64                 validators.isValidEmail(email, None)
    65             except validators.ValidationError:
    66                 sys.stderr.write("Error: That e-mail address is invalid.\n")
    67                 email = None
    68             else:
    69                 break
    70         while 1:
    71             if not password:
    72                 password = getpass.getpass()
    73                 password2 = getpass.getpass('Password (again): ')
    74                 if password != password2:
    75                     sys.stderr.write("Error: Your passwords didn't match.\n")
    76                     password = None
    77                     continue
    78             if password.strip() == '':
    79                 sys.stderr.write("Error: Blank passwords aren't allowed.\n")
    80                 password = None
    81                 continue
    82             break
    83     except KeyboardInterrupt:
    84         sys.stderr.write("\nOperation cancelled.\n")
    85         sys.exit(1)
    86     u = User.objects.create_user(username, email, password)
    87     u.is_staff = True
    88     u.is_active = True
    89     u.is_superuser = True
    90     u.save()
    91     print "Superuser created successfully."
    92 
    93 if __name__ == "__main__":
    94     createsuperuser()
  • django/contrib/auth/models.py

     
    116116        user.save()
    117117        return user
    118118
     119    def create_superuser(self, username, email, password):
     120        u = self.create_user(username, email, password)
     121        u.is_staff = True
     122        u.is_active = True
     123        u.is_superuser = True
     124        u.save()
     125
    119126    def make_random_password(self, length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'):
    120127        "Generates a random password with the given length and given allowed_chars"
    121128        # Note that default value of allowed_chars does not have "I" or letters
  • django/contrib/auth/management/commands/createsuperuser.py

     
     1from django.core.management.base import BaseCommand
     2from optparse import make_option
     3
     4"""
     5Helper function for creating superusers in the authentication system.
     6
     7If this management command is run, this command lets you create a superuser
     8interactively.
     9"""
     10
     11from django.core import validators
     12from django.contrib.auth.models import User
     13import getpass
     14import os
     15import sys
     16import re
     17
     18RE_VALID_USERNAME = re.compile('\w+$')
     19
     20def createsuperuser(username=None, email=None, password=None):
     21    """
     22    Helper function for creating a superuser from the command line. All
     23    arguments are optional and will be prompted-for if invalid or not given.
     24    """
     25    try:
     26        import pwd
     27    except ImportError:
     28        default_username = ''
     29    else:
     30        # Determine the current system user's username, to use as a default.
     31        default_username = pwd.getpwuid(os.getuid())[0].replace(' ', '').lower()
     32
     33    # Determine whether the default username is taken, so we don't display
     34    # it as an option.
     35    if default_username:
     36        try:
     37            User.objects.get(username=default_username)
     38        except User.DoesNotExist:
     39            pass
     40        else:
     41            default_username = ''
     42
     43    try:
     44        while 1:
     45            if not username:
     46                input_msg = 'Username'
     47                if default_username:
     48                    input_msg += ' (Leave blank to use %r)' % default_username
     49                username = raw_input(input_msg + ': ')
     50            if default_username and username == '':
     51                username = default_username
     52            if not RE_VALID_USERNAME.match(username):
     53                sys.stderr.write("Error: That username is invalid. Use only letters, digits and underscores.\n")
     54                username = None
     55                continue
     56            try:
     57                User.objects.get(username=username)
     58            except User.DoesNotExist:
     59                break
     60            else:
     61                sys.stderr.write("Error: That username is already taken.\n")
     62                username = None
     63        while 1:
     64            if not email:
     65                email = raw_input('E-mail address: ')
     66            try:
     67                validators.isValidEmail(email, None)
     68            except validators.ValidationError:
     69                sys.stderr.write("Error: That e-mail address is invalid.\n")
     70                email = None
     71            else:
     72                break
     73        while 1:
     74            if not password:
     75                password = getpass.getpass()
     76                password2 = getpass.getpass('Password (again): ')
     77                if password != password2:
     78                    sys.stderr.write("Error: Your passwords didn't match.\n")
     79                    password = None
     80                    continue
     81            if password.strip() == '':
     82                sys.stderr.write("Error: Blank passwords aren't allowed.\n")
     83                password = None
     84                continue
     85            break
     86    except KeyboardInterrupt:
     87        sys.stderr.write("\nOperation cancelled.\n")
     88        sys.exit(1)
     89    User.objects.create_superuser(username, email, password)
     90    print "Superuser created successfully."
     91
     92class Command(BaseCommand):
     93    option_list = BaseCommand.option_list + (
     94        make_option('--username', dest='username', default=None,
     95            help='Specifies the username for the superuser.'),
     96        make_option('--email', dest='email', default=None,
     97            help='Specifies the email address for the superuser.'),
     98    )
     99    help = 'Used to create a superuser.'
     100
     101    def handle(self, *args, **options):
     102        username = options.get('username', None)
     103        email = options.get('email', None)
     104
     105        createsuperuser(username=username, password=None, email=email)
     106
  • django/contrib/auth/management/__init__.py

     
     1"""
     2Creates permissions for all installed apps that need permissions.
     3"""
     4
     5from django.dispatch import dispatcher
     6from django.db.models import get_models, signals
     7from django.contrib.auth import models as auth_app
     8
     9def _get_permission_codename(action, opts):
     10    return u'%s_%s' % (action, opts.object_name.lower())
     11
     12def _get_all_permissions(opts):
     13    "Returns (codename, name) for all permissions in the given opts."
     14    perms = []
     15    for action in ('add', 'change', 'delete'):
     16        perms.append((_get_permission_codename(action, opts), u'Can %s %s' % (action, opts.verbose_name_raw)))
     17    return perms + list(opts.permissions)
     18
     19def create_permissions(app, created_models, verbosity):
     20    from django.contrib.contenttypes.models import ContentType
     21    from django.contrib.auth.models import Permission
     22    app_models = get_models(app)
     23    if not app_models:
     24        return
     25    for klass in app_models:
     26        ctype = ContentType.objects.get_for_model(klass)
     27        for codename, name in _get_all_permissions(klass._meta):
     28            p, created = Permission.objects.get_or_create(codename=codename, content_type__pk=ctype.id,
     29                defaults={'name': name, 'content_type': ctype})
     30            if created and verbosity >= 2:
     31                print "Adding permission '%s'" % p
     32
     33def create_superuser(app, created_models, verbosity, **kwargs):
     34    from django.contrib.auth.models import User
     35    from django.contrib.auth.management.commands.createsuperuser import createsuperuser as do_create
     36    if User in created_models and kwargs.get('interactive', True):
     37        msg = "\nYou just installed Django's auth system, which means you don't have " \
     38                "any superusers defined.\nWould you like to create one now? (yes/no): "
     39        confirm = raw_input(msg)
     40        while 1:
     41            if confirm not in ('yes', 'no'):
     42                confirm = raw_input('Please enter either "yes" or "no": ')
     43                continue
     44            if confirm == 'yes':
     45                do_create()
     46            break
     47
     48if 'create_permissions' not in [i.__name__ for i in dispatcher.getAllReceivers(signal=signals.post_syncdb)]:
     49    dispatcher.connect(create_permissions, signal=signals.post_syncdb)
     50if 'create_superuser' not in [i.__name__ for i in dispatcher.getAllReceivers(signal=signals.post_syncdb, sender=auth_app)]:
     51    dispatcher.connect(create_superuser, sender=auth_app, signal=signals.post_syncdb)
Back to Top