Code

Ticket #5614: create_superuser.diff

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

Refactored and fixed signals being registered twice in management/init.py

Line 
1Index: django/contrib/auth/management.py
2===================================================================
3--- django/contrib/auth/management.py   (revision 7027)
4+++ django/contrib/auth/management.py   (working copy)
5@@ -1,49 +0,0 @@
6-"""
7-Creates permissions for all installed apps that need permissions.
8-"""
9-
10-from django.dispatch import dispatcher
11-from django.db.models import get_models, signals
12-from django.contrib.auth import models as auth_app
13-
14-def _get_permission_codename(action, opts):
15-    return u'%s_%s' % (action, opts.object_name.lower())
16-
17-def _get_all_permissions(opts):
18-    "Returns (codename, name) for all permissions in the given opts."
19-    perms = []
20-    for action in ('add', 'change', 'delete'):
21-        perms.append((_get_permission_codename(action, opts), u'Can %s %s' % (action, opts.verbose_name_raw)))
22-    return perms + list(opts.permissions)
23-
24-def create_permissions(app, created_models, verbosity):
25-    from django.contrib.contenttypes.models import ContentType
26-    from django.contrib.auth.models import Permission
27-    app_models = get_models(app)
28-    if not app_models:
29-        return
30-    for klass in app_models:
31-        ctype = ContentType.objects.get_for_model(klass)
32-        for codename, name in _get_all_permissions(klass._meta):
33-            p, created = Permission.objects.get_or_create(codename=codename, content_type__pk=ctype.id,
34-                defaults={'name': name, 'content_type': ctype})
35-            if created and verbosity >= 2:
36-                print "Adding permission '%s'" % p
37-
38-def create_superuser(app, created_models, verbosity, **kwargs):
39-    from django.contrib.auth.models import User
40-    from django.contrib.auth.create_superuser import createsuperuser as do_create
41-    if User in created_models and kwargs.get('interactive', True):
42-        msg = "\nYou just installed Django's auth system, which means you don't have " \
43-                "any superusers defined.\nWould you like to create one now? (yes/no): "
44-        confirm = raw_input(msg)
45-        while 1:
46-            if confirm not in ('yes', 'no'):
47-                confirm = raw_input('Please enter either "yes" or "no": ')
48-                continue
49-            if confirm == 'yes':
50-                do_create()
51-            break
52-
53-dispatcher.connect(create_permissions, signal=signals.post_syncdb)
54-dispatcher.connect(create_superuser, sender=auth_app, signal=signals.post_syncdb)
55Index: django/contrib/auth/create_superuser.py
56===================================================================
57--- django/contrib/auth/create_superuser.py     (revision 7027)
58+++ django/contrib/auth/create_superuser.py     (working copy)
59@@ -1,94 +0,0 @@
60-"""
61-Helper function for creating superusers in the authentication system.
62-
63-If run from the command line, this module lets you create a superuser
64-interactively.
65-"""
66-
67-from django.core import validators
68-from django.contrib.auth.models import User
69-import getpass
70-import os
71-import sys
72-import re
73-
74-RE_VALID_USERNAME = re.compile('\w+$')
75-
76-def createsuperuser(username=None, email=None, password=None):
77-    """
78-    Helper function for creating a superuser from the command line. All
79-    arguments are optional and will be prompted-for if invalid or not given.
80-    """
81-    try:
82-        import pwd
83-    except ImportError:
84-        default_username = ''
85-    else:
86-        # Determine the current system user's username, to use as a default.
87-        default_username = pwd.getpwuid(os.getuid())[0].replace(' ', '').lower()
88-
89-    # Determine whether the default username is taken, so we don't display
90-    # it as an option.
91-    if default_username:
92-        try:
93-            User.objects.get(username=default_username)
94-        except User.DoesNotExist:
95-            pass
96-        else:
97-            default_username = ''
98-
99-    try:
100-        while 1:
101-            if not username:
102-                input_msg = 'Username'
103-                if default_username:
104-                    input_msg += ' (Leave blank to use %r)' % default_username
105-                username = raw_input(input_msg + ': ')
106-            if default_username and username == '':
107-                username = default_username
108-            if not RE_VALID_USERNAME.match(username):
109-                sys.stderr.write("Error: That username is invalid. Use only letters, digits and underscores.\n")
110-                username = None
111-                continue
112-            try:
113-                User.objects.get(username=username)
114-            except User.DoesNotExist:
115-                break
116-            else:
117-                sys.stderr.write("Error: That username is already taken.\n")
118-                username = None
119-        while 1:
120-            if not email:
121-                email = raw_input('E-mail address: ')
122-            try:
123-                validators.isValidEmail(email, None)
124-            except validators.ValidationError:
125-                sys.stderr.write("Error: That e-mail address is invalid.\n")
126-                email = None
127-            else:
128-                break
129-        while 1:
130-            if not password:
131-                password = getpass.getpass()
132-                password2 = getpass.getpass('Password (again): ')
133-                if password != password2:
134-                    sys.stderr.write("Error: Your passwords didn't match.\n")
135-                    password = None
136-                    continue
137-            if password.strip() == '':
138-                sys.stderr.write("Error: Blank passwords aren't allowed.\n")
139-                password = None
140-                continue
141-            break
142-    except KeyboardInterrupt:
143-        sys.stderr.write("\nOperation cancelled.\n")
144-        sys.exit(1)
145-    u = User.objects.create_user(username, email, password)
146-    u.is_staff = True
147-    u.is_active = True
148-    u.is_superuser = True
149-    u.save()
150-    print "Superuser created successfully."
151-
152-if __name__ == "__main__":
153-    createsuperuser()
154Index: django/contrib/auth/models.py
155===================================================================
156--- django/contrib/auth/models.py       (revision 7027)
157+++ django/contrib/auth/models.py       (working copy)
158@@ -116,6 +116,13 @@
159         user.save()
160         return user
161 
162+    def create_superuser(self, username, email, password):
163+        u = self.create_user(username, email, password)
164+        u.is_staff = True
165+        u.is_active = True
166+        u.is_superuser = True
167+        u.save()
168+
169     def make_random_password(self, length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'):
170         "Generates a random password with the given length and given allowed_chars"
171         # Note that default value of allowed_chars does not have "I" or letters
172Index: django/contrib/auth/management/commands/__init__.py
173===================================================================
174Index: django/contrib/auth/management/commands/createsuperuser.py
175===================================================================
176--- django/contrib/auth/management/commands/createsuperuser.py  (revision 0)
177+++ django/contrib/auth/management/commands/createsuperuser.py  (revision 0)
178@@ -0,0 +1,106 @@
179+from django.core.management.base import BaseCommand
180+from optparse import make_option
181+
182+"""
183+Helper function for creating superusers in the authentication system.
184+
185+If this management command is run, this command lets you create a superuser
186+interactively.
187+"""
188+
189+from django.core import validators
190+from django.contrib.auth.models import User
191+import getpass
192+import os
193+import sys
194+import re
195+
196+RE_VALID_USERNAME = re.compile('\w+$')
197+
198+def createsuperuser(username=None, email=None, password=None):
199+    """
200+    Helper function for creating a superuser from the command line. All
201+    arguments are optional and will be prompted-for if invalid or not given.
202+    """
203+    try:
204+        import pwd
205+    except ImportError:
206+        default_username = ''
207+    else:
208+        # Determine the current system user's username, to use as a default.
209+        default_username = pwd.getpwuid(os.getuid())[0].replace(' ', '').lower()
210+
211+    # Determine whether the default username is taken, so we don't display
212+    # it as an option.
213+    if default_username:
214+        try:
215+            User.objects.get(username=default_username)
216+        except User.DoesNotExist:
217+            pass
218+        else:
219+            default_username = ''
220+
221+    try:
222+        while 1:
223+            if not username:
224+                input_msg = 'Username'
225+                if default_username:
226+                    input_msg += ' (Leave blank to use %r)' % default_username
227+                username = raw_input(input_msg + ': ')
228+            if default_username and username == '':
229+                username = default_username
230+            if not RE_VALID_USERNAME.match(username):
231+                sys.stderr.write("Error: That username is invalid. Use only letters, digits and underscores.\n")
232+                username = None
233+                continue
234+            try:
235+                User.objects.get(username=username)
236+            except User.DoesNotExist:
237+                break
238+            else:
239+                sys.stderr.write("Error: That username is already taken.\n")
240+                username = None
241+        while 1:
242+            if not email:
243+                email = raw_input('E-mail address: ')
244+            try:
245+                validators.isValidEmail(email, None)
246+            except validators.ValidationError:
247+                sys.stderr.write("Error: That e-mail address is invalid.\n")
248+                email = None
249+            else:
250+                break
251+        while 1:
252+            if not password:
253+                password = getpass.getpass()
254+                password2 = getpass.getpass('Password (again): ')
255+                if password != password2:
256+                    sys.stderr.write("Error: Your passwords didn't match.\n")
257+                    password = None
258+                    continue
259+            if password.strip() == '':
260+                sys.stderr.write("Error: Blank passwords aren't allowed.\n")
261+                password = None
262+                continue
263+            break
264+    except KeyboardInterrupt:
265+        sys.stderr.write("\nOperation cancelled.\n")
266+        sys.exit(1)
267+    User.objects.create_superuser(username, email, password)
268+    print "Superuser created successfully."
269+
270+class Command(BaseCommand):
271+    option_list = BaseCommand.option_list + (
272+        make_option('--username', dest='username', default=None,
273+            help='Specifies the username for the superuser.'),
274+        make_option('--email', dest='email', default=None,
275+            help='Specifies the email address for the superuser.'),
276+    )
277+    help = 'Used to create a superuser.'
278+
279+    def handle(self, *args, **options):
280+        username = options.get('username', None)
281+        email = options.get('email', None)
282+
283+        createsuperuser(username=username, password=None, email=email)
284+