Code

Ticket #5614: create_superuser.3.diff

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

After seeing the discussion on django-developers made create_superuser.py backwards compatible

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 +1,9 @@
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+from django.contrib.auth.management.commands.createsuperuser import createsuperuser
74 
75-RE_VALID_USERNAME = re.compile('\w+$')
76-
77-def createsuperuser(username=None, email=None, password=None):
78-    """
79-    Helper function for creating a superuser from the command line. All
80-    arguments are optional and will be prompted-for if invalid or not given.
81-    """
82-    try:
83-        import pwd
84-    except ImportError:
85-        default_username = ''
86-    else:
87-        # Determine the current system user's username, to use as a default.
88-        default_username = pwd.getpwuid(os.getuid())[0].replace(' ', '').lower()
89-
90-    # Determine whether the default username is taken, so we don't display
91-    # it as an option.
92-    if default_username:
93-        try:
94-            User.objects.get(username=default_username)
95-        except User.DoesNotExist:
96-            pass
97-        else:
98-            default_username = ''
99-
100-    try:
101-        while 1:
102-            if not username:
103-                input_msg = 'Username'
104-                if default_username:
105-                    input_msg += ' (Leave blank to use %r)' % default_username
106-                username = raw_input(input_msg + ': ')
107-            if default_username and username == '':
108-                username = default_username
109-            if not RE_VALID_USERNAME.match(username):
110-                sys.stderr.write("Error: That username is invalid. Use only letters, digits and underscores.\n")
111-                username = None
112-                continue
113-            try:
114-                User.objects.get(username=username)
115-            except User.DoesNotExist:
116-                break
117-            else:
118-                sys.stderr.write("Error: That username is already taken.\n")
119-                username = None
120-        while 1:
121-            if not email:
122-                email = raw_input('E-mail address: ')
123-            try:
124-                validators.isValidEmail(email, None)
125-            except validators.ValidationError:
126-                sys.stderr.write("Error: That e-mail address is invalid.\n")
127-                email = None
128-            else:
129-                break
130-        while 1:
131-            if not password:
132-                password = getpass.getpass()
133-                password2 = getpass.getpass('Password (again): ')
134-                if password != password2:
135-                    sys.stderr.write("Error: Your passwords didn't match.\n")
136-                    password = None
137-                    continue
138-            if password.strip() == '':
139-                sys.stderr.write("Error: Blank passwords aren't allowed.\n")
140-                password = None
141-                continue
142-            break
143-    except KeyboardInterrupt:
144-        sys.stderr.write("\nOperation cancelled.\n")
145-        sys.exit(1)
146-    u = User.objects.create_user(username, email, password)
147-    u.is_staff = True
148-    u.is_active = True
149-    u.is_superuser = True
150-    u.save()
151-    print "Superuser created successfully."
152-
153 if __name__ == "__main__":
154     createsuperuser()
155Index: django/contrib/auth/models.py
156===================================================================
157--- django/contrib/auth/models.py       (revision 7027)
158+++ django/contrib/auth/models.py       (working copy)
159@@ -116,6 +116,13 @@
160         user.save()
161         return user
162 
163+    def create_superuser(self, username, email, password):
164+        u = self.create_user(username, email, password)
165+        u.is_staff = True
166+        u.is_active = True
167+        u.is_superuser = True
168+        u.save()
169+
170     def make_random_password(self, length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'):
171         "Generates a random password with the given length and given allowed_chars"
172         # Note that default value of allowed_chars does not have "I" or letters
173Index: django/contrib/auth/management/commands/__init__.py
174===================================================================
175Index: django/contrib/auth/management/commands/createsuperuser.py
176===================================================================
177--- django/contrib/auth/management/commands/createsuperuser.py  (revision 0)
178+++ django/contrib/auth/management/commands/createsuperuser.py  (revision 0)
179@@ -0,0 +1,106 @@
180+from django.core.management.base import BaseCommand
181+from optparse import make_option
182+
183+"""
184+Helper function for creating superusers in the authentication system.
185+
186+If this management command is run, this command lets you create a superuser
187+interactively.
188+"""
189+
190+from django.core import validators
191+from django.contrib.auth.models import User
192+import getpass
193+import os
194+import sys
195+import re
196+
197+RE_VALID_USERNAME = re.compile('\w+$')
198+
199+def createsuperuser(username=None, email=None, password=None):
200+    """
201+    Helper function for creating a superuser from the command line. All
202+    arguments are optional and will be prompted-for if invalid or not given.
203+    """
204+    try:
205+        import pwd
206+    except ImportError:
207+        default_username = ''
208+    else:
209+        # Determine the current system user's username, to use as a default.
210+        default_username = pwd.getpwuid(os.getuid())[0].replace(' ', '').lower()
211+
212+    # Determine whether the default username is taken, so we don't display
213+    # it as an option.
214+    if default_username:
215+        try:
216+            User.objects.get(username=default_username)
217+        except User.DoesNotExist:
218+            pass
219+        else:
220+            default_username = ''
221+
222+    try:
223+        while 1:
224+            if not username:
225+                input_msg = 'Username'
226+                if default_username:
227+                    input_msg += ' (Leave blank to use %r)' % default_username
228+                username = raw_input(input_msg + ': ')
229+            if default_username and username == '':
230+                username = default_username
231+            if not RE_VALID_USERNAME.match(username):
232+                sys.stderr.write("Error: That username is invalid. Use only letters, digits and underscores.\n")
233+                username = None
234+                continue
235+            try:
236+                User.objects.get(username=username)
237+            except User.DoesNotExist:
238+                break
239+            else:
240+                sys.stderr.write("Error: That username is already taken.\n")
241+                username = None
242+        while 1:
243+            if not email:
244+                email = raw_input('E-mail address: ')
245+            try:
246+                validators.isValidEmail(email, None)
247+            except validators.ValidationError:
248+                sys.stderr.write("Error: That e-mail address is invalid.\n")
249+                email = None
250+            else:
251+                break
252+        while 1:
253+            if not password:
254+                password = getpass.getpass()
255+                password2 = getpass.getpass('Password (again): ')
256+                if password != password2:
257+                    sys.stderr.write("Error: Your passwords didn't match.\n")
258+                    password = None
259+                    continue
260+            if password.strip() == '':
261+                sys.stderr.write("Error: Blank passwords aren't allowed.\n")
262+                password = None
263+                continue
264+            break
265+    except KeyboardInterrupt:
266+        sys.stderr.write("\nOperation cancelled.\n")
267+        sys.exit(1)
268+    User.objects.create_superuser(username, email, password)
269+    print "Superuser created successfully."
270+
271+class Command(BaseCommand):
272+    option_list = BaseCommand.option_list + (
273+        make_option('--username', dest='username', default=None,
274+            help='Specifies the username for the superuser.'),
275+        make_option('--email', dest='email', default=None,
276+            help='Specifies the email address for the superuser.'),
277+    )
278+    help = 'Used to create a superuser.'
279+
280+    def handle(self, *args, **options):
281+        username = options.get('username', None)
282+        email = options.get('email', None)
283+
284+        createsuperuser(username=username, password=None, email=email)
285+
286Index: django/contrib/auth/management/__init__.py
287===================================================================
288--- django/contrib/auth/management/__init__.py  (revision 0)
289+++ django/contrib/auth/management/__init__.py  (revision 0)
290@@ -0,0 +1,51 @@
291+"""
292+Creates permissions for all installed apps that need permissions.
293+"""
294+
295+from django.dispatch import dispatcher
296+from django.db.models import get_models, signals
297+from django.contrib.auth import models as auth_app
298+
299+def _get_permission_codename(action, opts):
300+    return u'%s_%s' % (action, opts.object_name.lower())
301+
302+def _get_all_permissions(opts):
303+    "Returns (codename, name) for all permissions in the given opts."
304+    perms = []
305+    for action in ('add', 'change', 'delete'):
306+        perms.append((_get_permission_codename(action, opts), u'Can %s %s' % (action, opts.verbose_name_raw)))
307+    return perms + list(opts.permissions)
308+
309+def create_permissions(app, created_models, verbosity):
310+    from django.contrib.contenttypes.models import ContentType
311+    from django.contrib.auth.models import Permission
312+    app_models = get_models(app)
313+    if not app_models:
314+        return
315+    for klass in app_models:
316+        ctype = ContentType.objects.get_for_model(klass)
317+        for codename, name in _get_all_permissions(klass._meta):
318+            p, created = Permission.objects.get_or_create(codename=codename, content_type__pk=ctype.id,
319+                defaults={'name': name, 'content_type': ctype})
320+            if created and verbosity >= 2:
321+                print "Adding permission '%s'" % p
322+
323+def create_superuser(app, created_models, verbosity, **kwargs):
324+    from django.contrib.auth.models import User
325+    from django.contrib.auth.management.commands.createsuperuser import createsuperuser as do_create
326+    if User in created_models and kwargs.get('interactive', True):
327+        msg = "\nYou just installed Django's auth system, which means you don't have " \
328+                "any superusers defined.\nWould you like to create one now? (yes/no): "
329+        confirm = raw_input(msg)
330+        while 1:
331+            if confirm not in ('yes', 'no'):
332+                confirm = raw_input('Please enter either "yes" or "no": ')
333+                continue
334+            if confirm == 'yes':
335+                do_create()
336+            break
337+
338+if 'create_permissions' not in [i.__name__ for i in dispatcher.getAllReceivers(signal=signals.post_syncdb)]:
339+    dispatcher.connect(create_permissions, signal=signals.post_syncdb)
340+if 'create_superuser' not in [i.__name__ for i in dispatcher.getAllReceivers(signal=signals.post_syncdb, sender=auth_app)]:
341+    dispatcher.connect(create_superuser, sender=auth_app, signal=signals.post_syncdb)