~ubuntu-branches/debian/sid/python-django/sid

« back to all changes in this revision

Viewing changes to django/contrib/auth/management/__init__.py

  • Committer: Package Import Robot
  • Author(s): Raphaël Hertzog
  • Date: 2014-09-17 14:15:11 UTC
  • mfrom: (1.3.17) (6.2.18 experimental)
  • Revision ID: package-import@ubuntu.com-20140917141511-icneokthe9ww5sk4
Tags: 1.7-2
* Release to unstable.
* Add a migrate-south sample script to help users apply their South
  migrations. Thanks to Brian May.

Show diffs side-by-side

added added

removed removed

Lines of Context:
6
6
import getpass
7
7
import unicodedata
8
8
 
9
 
from django.contrib.auth import (models as auth_app, get_permission_codename,
10
 
    get_user_model)
 
9
from django.apps import apps
 
10
from django.contrib.auth import models as auth_app, get_permission_codename
11
11
from django.core import exceptions
12
12
from django.core.management.base import CommandError
13
13
from django.db import DEFAULT_DB_ALIAS, router
14
 
from django.db.models import get_model, get_models, signals, UnavailableApp
 
14
from django.db.models import signals
15
15
from django.utils.encoding import DEFAULT_LOCALE_ENCODING
16
16
from django.utils import six
17
 
from django.utils.six.moves import input
18
17
 
19
18
 
20
19
def _get_all_permissions(opts, ctype):
30
29
def _get_builtin_permissions(opts):
31
30
    """
32
31
    Returns (codename, name) for all autogenerated permissions.
 
32
    By default, this is ('add', 'change', 'delete')
33
33
    """
34
34
    perms = []
35
 
    for action in ('add', 'change', 'delete'):
 
35
    for action in opts.default_permissions:
36
36
        perms.append((get_permission_codename(action, opts),
37
37
            'Can %s %s' % (action, opts.verbose_name_raw)))
38
38
    return perms
58
58
        pool.add(codename)
59
59
 
60
60
 
61
 
def create_permissions(app, created_models, verbosity, db=DEFAULT_DB_ALIAS, **kwargs):
 
61
def create_permissions(app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, **kwargs):
 
62
    if not app_config.models_module:
 
63
        return
 
64
 
62
65
    try:
63
 
        get_model('auth', 'Permission')
64
 
    except UnavailableApp:
 
66
        Permission = apps.get_model('auth', 'Permission')
 
67
    except LookupError:
65
68
        return
66
69
 
67
 
    if not router.allow_syncdb(db, auth_app.Permission):
 
70
    if not router.allow_migrate(using, Permission):
68
71
        return
69
72
 
70
73
    from django.contrib.contenttypes.models import ContentType
71
74
 
72
 
    app_models = get_models(app)
73
 
 
74
75
    # This will hold the permissions we're looking for as
75
76
    # (content_type, (codename, name))
76
77
    searched_perms = list()
77
78
    # The codenames and ctypes that should exist.
78
79
    ctypes = set()
79
 
    for klass in app_models:
 
80
    for klass in app_config.get_models():
80
81
        # Force looking up the content types in the current database
81
82
        # before creating foreign keys to them.
82
 
        ctype = ContentType.objects.db_manager(db).get_for_model(klass)
 
83
        ctype = ContentType.objects.db_manager(using).get_for_model(klass)
83
84
        ctypes.add(ctype)
84
85
        for perm in _get_all_permissions(klass._meta, ctype):
85
86
            searched_perms.append((ctype, perm))
87
88
    # Find all the Permissions that have a content_type for a model we're
88
89
    # looking for.  We don't need to check for codenames since we already have
89
90
    # a list of the ones we're going to create.
90
 
    all_perms = set(auth_app.Permission.objects.using(db).filter(
 
91
    all_perms = set(Permission.objects.using(using).filter(
91
92
        content_type__in=ctypes,
92
93
    ).values_list(
93
94
        "content_type", "codename"
94
95
    ))
95
96
 
96
97
    perms = [
97
 
        auth_app.Permission(codename=codename, name=name, content_type=ctype)
98
 
        for ctype, (codename, name) in searched_perms
99
 
        if (ctype.pk, codename) not in all_perms
 
98
        Permission(codename=codename, name=name, content_type=ct)
 
99
        for ct, (codename, name) in searched_perms
 
100
        if (ct.pk, codename) not in all_perms
100
101
    ]
101
 
    auth_app.Permission.objects.using(db).bulk_create(perms)
 
102
    # Validate the permissions before bulk_creation to avoid cryptic
 
103
    # database error when the verbose_name is longer than 50 characters
 
104
    permission_name_max_length = Permission._meta.get_field('name').max_length
 
105
    verbose_name_max_length = permission_name_max_length - 11  # len('Can change ') prefix
 
106
    for perm in perms:
 
107
        if len(perm.name) > permission_name_max_length:
 
108
            raise exceptions.ValidationError(
 
109
                "The verbose_name of %s is longer than %s characters" % (
 
110
                    perm.content_type,
 
111
                    verbose_name_max_length,
 
112
                )
 
113
            )
 
114
    Permission.objects.using(using).bulk_create(perms)
102
115
    if verbosity >= 2:
103
116
        for perm in perms:
104
117
            print("Adding permission '%s'" % perm)
105
118
 
106
119
 
107
 
def create_superuser(app, created_models, verbosity, db, **kwargs):
108
 
    try:
109
 
        get_model('auth', 'Permission')
110
 
        UserModel = get_user_model()
111
 
    except UnavailableApp:
112
 
        return
113
 
 
114
 
    from django.core.management import call_command
115
 
 
116
 
    if UserModel in created_models and kwargs.get('interactive', True):
117
 
        msg = ("\nYou just installed Django's auth system, which means you "
118
 
            "don't have any superusers defined.\nWould you like to create one "
119
 
            "now? (yes/no): ")
120
 
        confirm = input(msg)
121
 
        while 1:
122
 
            if confirm not in ('yes', 'no'):
123
 
                confirm = input('Please enter either "yes" or "no": ')
124
 
                continue
125
 
            if confirm == 'yes':
126
 
                call_command("createsuperuser", interactive=True, database=db)
127
 
            break
128
 
 
129
 
 
130
120
def get_system_username():
131
121
    """
132
122
    Try to determine the current system user's username.
166
156
 
167
157
    default_username = get_system_username()
168
158
    try:
169
 
        default_username = unicodedata.normalize('NFKD', default_username)\
170
 
            .encode('ascii', 'ignore').decode('ascii').replace(' ', '').lower()
 
159
        default_username = (unicodedata.normalize('NFKD', default_username)
 
160
                .encode('ascii', 'ignore').decode('ascii')
 
161
                .replace(' ', '').lower())
171
162
    except UnicodeDecodeError:
172
163
        return ''
173
164
 
187
178
            return ''
188
179
    return default_username
189
180
 
190
 
signals.post_syncdb.connect(create_permissions,
 
181
 
 
182
signals.post_migrate.connect(create_permissions,
191
183
    dispatch_uid="django.contrib.auth.management.create_permissions")
192
 
signals.post_syncdb.connect(create_superuser,
193
 
    sender=auth_app, dispatch_uid="django.contrib.auth.management.create_superuser")