def execute(self, *args, **options):
        logger.info("Synchronize django permissions")

        for app_config in apps.get_app_configs():
            create_permissions(app_config, verbosity=options['verbosity'])

        logger.info("Done.")

        logger.info("Synchronize mapentity permissions")

        # Make sure apps are registered at this point
        import_module(settings.ROOT_URLCONF)

        # Tests reset DB so we have to reset this cache too
        clear_internal_user_cache()

        # For all models registered, add missing bits
        for model in registry.registry.keys():
            if not model._meta.abstract:
                create_mapentity_model_permissions(model)

        logger.info("Done.")

        logger.info("Synchronize geotrek permissions")

        for content_type in ContentType.objects.all():
            model = content_type.model_class()
            if model and issubclass(model, BasePublishableMixin) and not model._meta.abstract:
                Permission.objects.get_or_create(
                    codename='publish_%s' % content_type.model,
                    content_type=content_type,
                    defaults={'name': 'Can publish %s' % content_type.name}
                )

        logger.info("Done.")
Exemplo n.º 2
0
def add_admin_perms(models, perm_parts=('add', 'change', 'delete')):
    """Designed to be run from a data migration script,
    adds create, edit and delete permissions to the site admin group"""
    from django.contrib.contenttypes.management import update_contenttypes
    from django.contrib.contenttypes.models import ContentType
    from django.contrib.auth.management import create_permissions
    from django.apps import apps
    from django.contrib.auth.models import Group, Permission

    if not isinstance(models, tuple):
        # Allow single model to be passed in
        models = (models,)

    # First, we need to create permissions in case this hasn't run yet
    # http://andrewingram.net/2012/dec/ \
    # common-pitfalls-django-south/#contenttypes-and-permissions
    app_set = set([model._meta.app_label for model in models])
    for app in app_set:
        app_config = apps.get_app_config(app)
        update_contenttypes(app_config)
        create_permissions(app_config)

    # Get group for site admin
    group, created = Group.objects.get_or_create(name='site admin')

    # Add permissions to the site admin
    for model in models:
        for perm_part in perm_parts:
            codename = "%s_%s" % (perm_part, model._meta.model_name)
            content_type = ContentType.objects.get_for_model(model)
            permission = Permission.objects.get(codename=codename,
                                                content_type=content_type)
            group.permissions.add(permission)

    group.save()
Exemplo n.º 3
0
def lazy_permission_creation(**kwargs):
    from .models import PermissionsMixin
    if issubclass(auth.get_user_model(), PermissionsMixin):
        return

    # Call through to Django's create_permissions
    create_permissions(**kwargs)
def create_realtime_rest_group(apps, schema_editor):
    """Populate Groups for realtime group.

    :param apps: App registry.
    :type apps: django.apps.apps

    :param schema_editor: Django db abstraction for turning model into db.
    :type schema_editor: django.db.backends.schema
    """
    # import apps registry, somehow it was only loaded fully from import
    realtime_app_config = apps_registry.get_app_config('realtime')
    # update content types
    update_contenttypes(realtime_app_config, interactive=False)
    # update permissions
    create_permissions(realtime_app_config, interactive=False)
    Group = apps.get_model('auth', 'Group')
    try:
        realtime_group = Group.objects.get(name=REST_GROUP)
    except Group.DoesNotExist:
        realtime_group = Group.objects.create(name=REST_GROUP)

    Permission = apps.get_model('auth', 'Permission')
    realtime_permissions = Permission.objects.filter(
        content_type__app_label='realtime')
    realtime_group.permissions.add(*realtime_permissions)
    realtime_group.save()
Exemplo n.º 5
0
    def test_duplicated_permissions(self):
        """
        Test that we show proper error message if we are trying to create
        duplicate permissions.
        """
        # check duplicated default permission
        models.Permission._meta.permissions = [
           ('change_permission', 'Can edit permission (duplicate)')]
        six.assertRaisesRegex(self, CommandError,
            "The permission codename 'change_permission' clashes with a "
            "builtin permission for model 'auth.Permission'.",
            create_permissions, models, [], verbosity=0)

        # check duplicated custom permissions
        models.Permission._meta.permissions = [
            ('my_custom_permission', 'Some permission'),
            ('other_one', 'Some other permission'),
            ('my_custom_permission', 'Some permission with duplicate permission code'),
        ]
        six.assertRaisesRegex(self, CommandError,
            "The permission codename 'my_custom_permission' is duplicated for model "
            "'auth.Permission'.",
            create_permissions, models, [], verbosity=0)

        # should not raise anything
        models.Permission._meta.permissions = [
            ('my_custom_permission', 'Some permission'),
            ('other_one', 'Some other permission'),
        ]
        create_permissions(models, [], verbosity=0)
    def handle(self, *args, **options):
        # Add any missing content types
        update_all_contenttypes()

        # Add any missing permissions
        for app in get_apps():
            create_permissions(app, None, 2)
def add_permissions(apps, schema_editor, with_create_permissions=True):

    teachers = Group.objects.get(name='teachers')
    students = Group.objects.get(name='students')
    try:
        can_add_booking = Permission.objects.get(name='Can add booking')
        can_delete_booking = Permission.objects.get(name='Can delete booking')
        can_change_booking = Permission.objects.get(name='Can change booking')

        teachers.permissions.add(
            can_add_booking,
            can_delete_booking,
            can_change_booking,
        )
    except Permission.DoesNotExist:
        if with_create_permissions:
            # Manually run create_permissions
            from django.contrib.auth.management import create_permissions
            assert not getattr(apps, 'models_module', None)
            apps.models_module = True
            create_permissions(apps, verbosity=0)
            apps.models_module = None
            return add_permissions(
                apps, schema_editor, with_create_permissions=False)
        else:
            raise

    teachers.save()
    students.save()
def create_default_permissions_group(apps, schema_editor):
    '''
    Create the 'mydata-default-permissions' group
    '''
    # First, we need to ensure that permissions have been created,
    # then we can create a group and assign those permissions to it:
    for app_config in apps.get_app_configs():
        app_config.models_module = True
        create_permissions(app_config, apps=apps, verbosity=0)
        app_config.models_module = None

    group = Group.objects.create(name='mydata-default-permissions')
    tardis_portal_app_permissions = [
        'add_instrument', 'change_instrument', 'add_experiment',
        'change_experiment', 'add_experimentparameterset', 'add_objectacl',
        'add_dataset', 'change_dataset', 'add_datafile']
    for perm in tardis_portal_app_permissions:
        group.permissions.add(
            Permission.objects.get(
                codename=perm, content_type__app_label='tardis_portal'))
    mydata_app_permissions = [
        'add_uploader', 'change_uploader',
        'add_uploaderregistrationrequest', 'change_uploaderregistrationrequest',
        'add_uploadersetting', 'change_uploadersetting']
    for perm in mydata_app_permissions:
        group.permissions.add(
            Permission.objects.get(
                codename=perm, content_type__app_label='mydata'))
Exemplo n.º 9
0
def make_groups(apps, schema_editor):
    # Create the default set of user groups and
    # assign the correct permissions.

    # Permissions aren't created until after all migrations
    # are run so lets create them now!
    app_configs = apps.get_app_configs()
    for app in app_configs:
        app.models_module = True
        create_permissions(app, verbosity=0)
        app.models_module = None

    Group = apps.get_model('auth', 'Group')
    Permission = apps.get_model('auth', 'Permission')

    for group in settings.DEFAULT_GROUPS:
        g,created = Group.objects.get_or_create(name=group)
        if group == 'admin':
            # Assign all available permissions to the admin group
            p = list(Permission.objects.all())
            g.permissions.add(*p)
        elif group == 'staff':
            for perm in settings.DEFAULT_STAFF_PERMISSIONS:
                p = Permission.objects.get(name=perm)
                g.permissions.add(p)
        elif group == 'user':
            # Default permissions for users are store in
            # the settings.py file
            for perm in settings.DEFAULT_USER_PERMISSIONS:
                p = Permission.objects.get(name=perm)
                g.permissions.add(p)
Exemplo n.º 10
0
def update_permissions_after_migration(app, **kwargs):
    """
    Update app permission just after every migration.
    """

    create_permissions(
        get_app(app), get_models(), 2 if settings.DEBUG else 0)
Exemplo n.º 11
0
def step2(request):
    if request.method == 'POST': # If the form has been submitted...
        form = WorkspaceCreationForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
	    name = form.cleaned_data['name']
	    workspace = MyTenantModel.objects.create(name=name)
	    Employee.objects.create(user=request.user, workspace=workspace)
	    
	    from django.contrib.contenttypes.models import ContentType
            from django.contrib.auth.management import create_permissions
	    from django.contrib.auth.models import Permission
            from django.db.models import get_app, get_models
            create_permissions(get_app('deleteissue'), get_models(), 0) ### should optimize by calling only the new models instead of get_models
	    #user = TenantUser.for_tenant(workspace).objects.create_user("*****@*****.**", "max")
	    user = request.user

	    ct = ContentType.objects.get_for_model(Project.for_tenant(workspace))
	    perm = Permission.objects.filter(content_type=ct)
	    for i in perm:
		user.user_permissions.add(i)

	    register_models_for_tenant(workspace)
	    return HttpResponseRedirect('/admin/') # Redirect after POST
    else:
        form = WorkspaceCreationForm() # An unbound form
    return render(request, 'step2.html', {'form': form, 'form_action': "/deleteissue/step2/"})
Exemplo n.º 12
0
    def execute(self, *args, **options):
        logger.info("Synchronize django permissions")

        for app in get_apps():
            create_permissions(app, [], int(options.get('verbosity', 1)))

        logger.info("Done.")

        logger.info("Synchronize mapentity permissions")

        # Make sure apps are registered at this point
        import_module(settings.ROOT_URLCONF)

        # For all models registered, add missing bits
        for model in registry.registry.keys():
            create_mapentity_model_permissions(model)

        logger.info("Done.")

        logger.info("Synchronize geotrek permissions")

        for content_type in ContentType.objects.all():
            model = content_type.model_class()
            if model and issubclass(model, BasePublishableMixin):
                Permission.objects.get_or_create(
                    codename='publish_%s' % content_type.model,
                    name='Can publish %s' % content_type.name,
                    content_type=content_type)

        logger.info("Done.")
Exemplo n.º 13
0
def update_permissions_after_migration(app, **kwargs):

    from django.conf import settings
    from django.db.models import get_app, get_models
    from django.contrib.auth.management import create_permissions
    
    create_permissions(get_app(app), get_models(), 2 if settings.DEBUG else 0)

    if app == "heliosinstitution":
        """
        Permissions must exist in app model, otherwise an error
        will be thrown
        """
        heliosinstitution_group_permissions = {
            "Institution Admin" : [
                "delegate_institution_mngt",
                "revoke_institution_mngt",
                "delegate_election_mngt",
                "revoke_election_mngt"
            ],
            "Election Admin": [
            ],
        }
        if verbosity>0:
            print "Initialising data post_migrate"
        for group in heliosinstitution_group_permissions:
            role, created = Group.objects.get_or_create(name=group)
            if verbosity > 1 and created:
                print 'Creating group', group
                for perm in heliosinstitution_group_permissions[group]:
                    role.permissions.add(Permission.objects.get(codename=perm))
                    if verbosity > 1:
                        print 'Permitting', group, 'to', perm
                        role.save()  
Exemplo n.º 14
0
def create_verifier_group(apps, schema, with_create_permissions=True):
    """
    Create a "verifiers" group that has the "can_verify" permission.
    All user created before July 11th 2015 are automatically added to this group.
    """
    Group = apps.get_model('auth', 'Group')
    Permission = apps.get_model('auth', 'Permission')
    User = apps.get_model('auth', 'User')
    ContentType = apps.get_model('contenttypes', 'ContentType')

    mp_content_type = ContentType.objects.get(app_label='campaigns', model='mp')
    try:  # Workaround for #23422
        can_verify = Permission.objects.get(codename='can_verify', content_type=mp_content_type)
    except Permission.DoesNotExist:
        if with_create_permissions:
            from django.contrib.auth.management import create_permissions
            assert not getattr(apps, 'models_module', None)
            apps.models_module = True
            create_permissions(apps, verbosity=0)
            apps.models_module = None
            return create_verifier_group(
                apps, schema, with_create_permissions=False)
        else:
            raise
    cutoff_date = timezone.make_aware(datetime(2015, 7, 11, 23, 59, 59))

    verifier_group = Group.objects.create(name="Verifiers")
    verifier_group.permissions.add(can_verify)

    for user in User.objects.filter(date_joined__lte=cutoff_date):
        user.groups.add(verifier_group)
Exemplo n.º 15
0
def update_permissions_after_migration(app, **kwargs):
    """
    Create permissions for apps synced with South even when do not change.

    Django creates new custom permissions (defined in a model's Meta class) when
    the app of that model gives a post_syncdb signal. South only fires that
    signal, however, when new migrations are applied to that app. So if any new
    permissions are added without any models changing (or, I suppose, a dummy
    migration is added), those new permission will not be created.

    Hooking to the post_migrate signal ensures that such new permissions will be
    created, along with the project specific permissions created from
    management.update_project_permissions.

    South bug: http://south.aeracode.org/ticket/211
    Adapted solution: http://devwithpassion.com/felipe/south-django-permissions/
    """

    from django.conf import settings
    from django.db.models import get_app, get_models
    from django.contrib.auth.management import create_permissions
    from .management import update_project_permissions
    
    create_permissions(get_app(app), get_models(), 2 if settings.DEBUG else 0)
    update_project_permissions()
Exemplo n.º 16
0
 def handle(self, *args, **options):
     if not args:
         apps = [get_app(model._meta.app_label) for model in get_models()]
     else:
         apps = [get_app(arg) for arg in args]
     for app in apps:
         create_permissions(app, get_models(), options.get('verbosity', 0))
def add_groups(apps, schema_editor, with_create_permissions=True):
    Group = apps.get_model('auth', 'Group')
    Permission = apps.get_model('auth', 'Permission')
    User = apps.get_model('auth', 'User')

    try:
        perms = dict(
            [(codename, Permission.objects.get(codename=codename))
             for codename in set(chain(*group_perms.values()))])
    except Permission.DoesNotExist:
        if with_create_permissions:
            # create_permissions runs in the post_migrate signal, at the end of
            # all migrations. If migrating a fresh database (such as during
            # tests), then manually run create_permissions.
            from django.contrib.auth.management import create_permissions
            assert not getattr(apps, 'models_module', None)
            apps.models_module = True
            create_permissions(apps, verbosity=0)
            apps.models_module = None
            return add_groups(
                apps, schema_editor, with_create_permissions=False)
        else:
            raise

    for group_name in sorted(group_perms.keys()):
        group = Group.objects.create(name=group_name)
        perm_list = [
            perms[codename] for codename in group_perms[group_name]]
        group.permissions.add(*perm_list)

    change_group = Group.objects.get(name='change-resource')
    for user in User.objects.all():
        user.groups.add(change_group)
def migrate_service_enabled(apps, schema_editor):
    for app_config in apps.get_app_configs():
        app_config.models_module = True
        create_permissions(app_config, apps=apps, verbosity=0)
        app_config.models_module = None

    Group = apps.get_model("auth", "Group")
    Permission = apps.get_model("auth", "Permission")
    Teamspeak3User = apps.get_model("teamspeak3", "Teamspeak3User")

    perm = Permission.objects.get(codename='access_teamspeak3')

    member_group_name = getattr(settings, str('DEFAULT_AUTH_GROUP'), 'Member')
    blue_group_name = getattr(settings, str('DEFAULT_BLUE_GROUP'), 'Blue')

    # Migrate members
    if Teamspeak3User.objects.filter(user__groups__name=member_group_name).exists() or \
            getattr(settings, str('ENABLE_AUTH_TEAMSPEAK3'), False):
        try:
            group = Group.objects.get(name=member_group_name)
            group.permissions.add(perm)
        except ObjectDoesNotExist:
            logger.warning('Failed to migrate ENABLE_AUTH_TEAMSPEAK3 setting')

    # Migrate blues
    if Teamspeak3User.objects.filter(user__groups__name=blue_group_name).exists() or \
            getattr(settings, str('ENABLE_BLUE_TEAMSPEAK3'), False):
        try:
            group = Group.objects.get(name=blue_group_name)
            group.permissions.add(perm)
        except ObjectDoesNotExist:
            logger.warning('Failed to migrate ENABLE_BLUE_TEAMSPEAK3 setting')
Exemplo n.º 19
0
def make_permissions(apps, schema_editor, with_create_permissions=True):
    db_alias = schema_editor.connection.alias
    Group = apps.get_model("auth", "Group")
    User = apps.get_model("auth", "User")
    Permission = apps.get_model("auth", "Permission")
    try:
        read_perm = Permission.objects.get(codename='read_nodegroup', content_type__app_label='models', content_type__model='nodegroup')
        write_perm = Permission.objects.using(db_alias).get(codename='write_nodegroup', content_type__app_label='models', content_type__model='nodegroup')
        delete_perm = Permission.objects.using(db_alias).get(codename='delete_nodegroup', content_type__app_label='models', content_type__model='nodegroup')
    except Permission.DoesNotExist:
        if with_create_permissions:
            # Manually run create_permissions
            from django.contrib.auth.management import create_permissions
            assert not getattr(apps, 'models_module', None)
            apps.models_module = True
            create_permissions(apps, verbosity=0)
            apps.models_module = None
            return make_permissions(
                apps, schema_editor, with_create_permissions=False)
        else:
            raise

    edit_group = Group.objects.using(db_alias).create(name='edit')
    edit_group.permissions.add(read_perm, write_perm, delete_perm)

    read_group = Group.objects.using(db_alias).create(name='read')
    read_group.permissions.add(read_perm)

    admin_user = User.objects.using(db_alias).get(username='******')
    admin_user.groups.add(edit_group)
    admin_user.groups.add(read_group)

    anonymous_user = User.objects.using(db_alias).get(username='******')
    anonymous_user.groups.add(read_group)
    def handle(self, *args, **options):

        apps = []
        for arg in args:
            apps.append(get_app(arg))

        for app in apps:
            create_permissions(app, None, options.get('verbosity', 0))
Exemplo n.º 21
0
    def forwards(self, orm):
        "Write your forwards methods here."
        # Note: Don't use "from appname.models import ModelName". 
        # Use orm.ModelName to refer to models in this application,
        # and orm['appname.ModelName'] for models in other applications.

        update_contenttypes(get_app('activities'), get_models())
        create_permissions(get_app('activities'), get_models(), 0)
Exemplo n.º 22
0
    def handle(self, *args, **options):
        from django.contrib.auth.management import create_permissions
        from django.db.models import get_apps, get_models

        verbosity = int(options['verbosity'])

        for app in get_apps():
            create_permissions(app, None, verbosity)
Exemplo n.º 23
0
def _make_permissions(apps, schema_editor):
    apps.models_module = True
    create_permissions(apps, verbosity=0)
    apps.models_module = None

    Group = apps.get_model("auth", "Group")

    create_farmers_group(Group)
Exemplo n.º 24
0
def create_all_permissions(**kwargs):
    create_permissions(**kwargs)
    for p in Permission.objects.filter(codename__startswith='change_'):
        res= Permission.objects.get_or_create(
            content_type=p.content_type,
            codename=p.codename.replace('change_','changeall_',1),
            name=p.name.replace('change','change ALL',1),
        )
Exemplo n.º 25
0
 def handle(self, *args, **options):
     setup_environ(Poem.settings)
     from django.contrib.auth.management import create_permissions
     from django.db.models import get_apps
     
     for app in get_apps():
         create_permissions(app, None, 2)
     logger.info('Permissions were successfully updated.')
def _make_permissions(apps, schema_editor):
    apps.models_module = True
    create_permissions(apps, verbosity=0)
    apps.models_module = None

    Group = apps.get_model("auth", "Group")
    Permission = apps.get_model("auth", "Permission")

    add_delivery_related_permissions(Group, Permission)
Exemplo n.º 27
0
def update_permissions_after_migration(app, **kwargs):
    """
    Update app permission just after every migration. This is based on the
    django_extensions' update_permissions management command.
    """
    from django.db.models import get_app, get_models
    from django.contrib.auth.management import create_permissions

    create_permissions(get_app(app), get_models(), 2)
Exemplo n.º 28
0
    def handle(self, *args, **options):
        self.stdout.write("Create permissions for:")

        verbosity=int(options.get('verbosity', 0))
        app_configs = apps.get_app_configs()
        for app_config in app_configs:
            app_label = app_config.label
            self.stdout.write(" * %s" % app_label)
            create_permissions(app_config, verbosity=verbosity)
Exemplo n.º 29
0
def create_permissions_compat(app, **kwargs):
    '''
    Creates permissions like syncdb would if we were not using South

    See http://south.aeracode.org/ticket/211
    '''
    from django.db.models import get_app
    from django.contrib.auth.management import create_permissions
    create_permissions(get_app(app), (), 0)
Exemplo n.º 30
0
def update_permissions_after_migration(app,**kwargs):
    """
    Update app permission just after every migration.
    """
    from django.conf import settings
    from django.db.models import get_app, get_models
    from django.contrib.auth.management import create_permissions

    create_permissions(get_app(app), get_models(), 2 if settings.DEBUG else 0)
Exemplo n.º 31
0
def create_groups(apps, schema_editor):
    """ Create groups and assign the permissions."""
    Group = apps.get_model('auth', 'Group')
    Permission = apps.get_model('auth', 'Permission')

    apps.models_module = True
    create_permissions(apps, verbosity=0)
    apps.models_module = None

    group, __ = Group.objects.get_or_create(name=Role.ADMINS)
    for codename in ['add_usercredential', 'change_usercredential']:
        permission = Permission.objects.get(codename=codename)
        group.permissions.add(permission)
 def test_unavailable_models(self):
     """
     #24075 - Permissions shouldn't be created or deleted if the ContentType
     or Permission models aren't available.
     """
     state = migrations.state.ProjectState()
     # Unavailable contenttypes.ContentType
     with self.assertNumQueries(0):
         create_permissions(self.app_config, verbosity=0, apps=state.apps)
     # Unavailable auth.Permission
     state = migrations.state.ProjectState(real_apps=['contenttypes'])
     with self.assertNumQueries(0):
         create_permissions(self.app_config, verbosity=0, apps=state.apps)
Exemplo n.º 33
0
 def test_create_permissions_checks_contenttypes_created(self):
     """
     `post_migrate` handler ordering isn't guaranteed. Simulate a case
     where create_permissions() is called before create_contenttypes().
     """
     # Warm the manager cache.
     ContentType.objects.get_for_model(Group)
     # Apply a deletion as if e.g. a database 'flush' had been executed.
     ContentType.objects.filter(app_label='auth', model='group').delete()
     # This fails with a foreign key constraint without the fix.
     create_permissions(apps.get_app_config('auth'),
                        interactive=False,
                        verbosity=0)
Exemplo n.º 34
0
 def forwards(self, orm):
     app = get_app('imagestore')
     create_permissions(app, (), 2)
     add_image_permission = Permission.objects.get_by_natural_key('add_image', 'imagestore', 'image')
     add_album_permission = Permission.objects.get_by_natural_key('add_album', 'imagestore', 'album')
     change_image_permission = Permission.objects.get_by_natural_key('change_image', 'imagestore', 'image')
     change_album_permission = Permission.objects.get_by_natural_key('change_album', 'imagestore', 'album')
     delete_image_permission = Permission.objects.get_by_natural_key('delete_image', 'imagestore','image')
     delete_album_permission = Permission.objects.get_by_natural_key('delete_album', 'imagestore', 'album')
     for user in User.objects.all():
         user.user_permissions.add(add_image_permission, add_album_permission,)
         user.user_permissions.add(change_image_permission, change_album_permission,)
         user.user_permissions.add(delete_image_permission, delete_album_permission,)
         user.save()
def add_all_permissions():
    """Enforce loading of perms

    See:
    https://stackoverflow.com/questions/29296757/django-data-migrate-permissions
    https://code.djangoproject.com/ticket/23422
    """
    from django.apps import apps
    from django.contrib.auth.management import create_permissions

    for app_config in apps.get_app_configs():
        app_config.models_module = True
        create_permissions(app_config, verbosity=0)
        app_config.models_module = None
Exemplo n.º 36
0
 def handle(self, *args, **options):
     if not args:
         apps = []
         for model in get_models():
             try:
                 apps.append(get_app(model._meta.app_label))
             except ImproperlyConfigured:
                 pass
     else:
         apps = []
         for arg in args:
             apps.append(get_app(arg))
     for app in apps:
         create_permissions(app, get_models(), options.get('verbosity', 0))
Exemplo n.º 37
0
def create_default_groups(apps, schema_editor):
    group = apps.get_model('openwisp_users', 'group')

    # To populate all the permissions
    for app_config in apps.get_app_configs():
        app_config.models_module = True
        create_permissions(app_config, apps=apps, verbosity=0)
        app_config.models_module = None

    operator = group.objects.filter(name='Operator')
    if operator.count() == 0:
        operator = group.objects.create(name='Operator')

    admin = group.objects.filter(name='Administrator')
    if admin.count() == 0:
        admin = group.objects.create(name='Administrator')
        permissions = [
            Permission.objects.get(content_type__app_label="openwisp_users",
                                   codename='add_user').pk,
            Permission.objects.get(content_type__app_label="openwisp_users",
                                   codename='change_user').pk,
            Permission.objects.get(
                content_type__app_label="openwisp_users",
                codename='change_organizationuser',
            ).pk,
            Permission.objects.get(
                content_type__app_label="openwisp_users",
                codename='delete_organizationuser',
            ).pk,
            Permission.objects.get(
                content_type__app_label="openwisp_users",
                codename='add_organizationuser',
            ).pk,
        ]
        try:
            permissions += [
                Permission.objects.get(
                    content_type__app_label="openwisp_users",
                    codename='view_user').pk,
                Permission.objects.get(
                    content_type__app_label="openwisp_users",
                    codename='view_group').pk,
                Permission.objects.get(
                    content_type__app_label="openwisp_users",
                    codename='view_organizationuser',
                ).pk,
            ]
        except Permission.DoesNotExist:
            pass
        admin.permissions.set(permissions)
Exemplo n.º 38
0
def add_permissions_to_groups(app, permissions):
    """Assign permissions to groups."""

    # Make sure that all app permissions are created.
    # Related to South bug http://south.aeracode.org/ticket/211
    app_obj = get_app(app)
    create_permissions(app_obj, get_models(app_mod=app_obj), verbosity=2)

    for perm_name, groups in permissions.iteritems():
        for group_name in groups:
            group, created = Group.objects.get_or_create(name=group_name)
            permission = Permission.objects.get(codename=perm_name,
                                                content_type__app_label=app)
            group.permissions.add(permission)
Exemplo n.º 39
0
    def manage(apps, schema_editor):
        from django.contrib.auth.models import Group, Permission
        from django.contrib.auth.management import create_permissions

        # Necessary to get the auto-gen model perms in place
        for app_config in apps.get_app_configs():
            app_config.models_module = True
            create_permissions(app_config, apps=apps, verbosity=0)
            app_config.models_module = None

        # This group may or may not exist, depending on our context (tests, prod, etc.)
        g, _ = Group.objects.get_or_create(name='forum_trust_level_1')
        p = Permission.objects.get(codename='add_plugin')
        g.permissions.add(p)
Exemplo n.º 40
0
def create_groups(apps, schema_editor):
    """ Create groups and assign the permissions."""
    Group = apps.get_model("auth", "Group")
    Permission = apps.get_model("auth", "Permission")

    for app_config in apps.get_app_configs():
        app_config.models_module = True
        create_permissions(app_config, verbosity=0, apps=apps)
        app_config.models_module = None

    group, __ = Group.objects.get_or_create(name=Role.ADMINS)
    for codename in ["add_usercredential", "change_usercredential"]:
        permission = Permission.objects.get(codename=codename)
        group.permissions.add(permission)
def forwards_func(apps, schema_editor):
    Group = apps.get_model('auth', 'Group')
    Perm = apps.get_model('auth', 'Permission')
    ContentType = apps.get_model('contenttypes', 'ContentType')

    for custom in MODELS:
        ContentType.objects.get(app_label='xds_api',
                                model=custom.replace(" ", "")).delete()
        ct = ContentType.objects.filter(model=custom.replace(" ", ""))
        if ct.exists():
            ct.delete()

    for app_config in apps.get_app_configs():
        app_config.models_module = True
        create_permissions(app_config, verbosity=0)
        app_config.models_module = None

    for app_config in apps.get_app_configs():
        app_config.models_module = True
        create_contenttypes(app_config, verbosity=0)
        app_config.models_module = None

    for group in GROUPS:
        new_group, created = Group.objects.get_or_create(name=group)

        for model in MODELS:
            for permission in PERMISSIONS:
                name = 'Can {} {}'.format(permission, model)
                print("Creating {}".format(name))

                model_comb = model
                value = model_comb.replace(" ", "")
                codename = '{}_{}'.format(permission, value)

                try:
                    content_type = \
                        ContentType.objects.get(model=value)
                    model_add_perm, created = \
                        Perm.objects.get_or_create(codename=codename,
                                                   name=name,
                                                   content_type=content_type)
                except Perm.DoesNotExist:
                    logging.warning(
                        "Permission not found with name '{}'.".format(name))
                    continue

                new_group.permissions.add(model_add_perm)

    print("Updated Course Information Mapping permissions.")
def add_trash_user_group(apps, schema_editor):
    '''
    Create the '__trashuser__'
    '''
    # First, we need to ensure that permissions have been created,
    # then we can create a group and assign those permissions to it:
    for app_config in apps.get_app_configs():
        app_config.models_module = True
        create_permissions(app_config, apps=apps, verbosity=0)
        app_config.models_module = None
    group = Group.objects.create(name='__trashcan__')
    user = User.objects.create(is_active=True, is_superuser=False, is_staff=False,
                               email='*****@*****.**', date_joined='1970-01-01T00:00:00Z',
                               last_login='******', name='__trashuser__')
    group.user_set.add(user)
Exemplo n.º 43
0
    def test_custom_permission_name_length(self):
        auth_app_config = apps.get_app_config('auth')

        ContentType.objects.get_by_natural_key('auth', 'permission')
        custom_perm_name = 'a' * 256
        Permission._meta.permissions = [
            ('my_custom_permission', custom_perm_name),
        ]
        try:
            msg = ("The permission name %s of auth.permission is longer than "
                   "255 characters" % custom_perm_name)
            with self.assertRaisesMessage(exceptions.ValidationError, msg):
                create_permissions(auth_app_config, verbosity=0)
        finally:
            Permission._meta.permissions = []
def add_in_progress_perm(apps, schema_editor):

    return
    try:
        permission = Permission.objects.get(codename="can_save_in_progress")
    except Permission.DoesNotExist:
        app_config = apps.get_app_config("qa")
        app_config.models_module = True
        create_permissions(app_config, verbosity=0)
        app_config.models_module = None

        permission = Permission.objects.get(codename="can_save_in_progress")

    for group in Group.objects.all():
        group.permissions.add(permission)
    def handle(self, *args, **options):
        if not args:
            apps = []
            for model in get_models():
                apps.append(get_app(model._meta.app_label))
        else:
            apps = []
            for arg in args:
                apps.append(get_app(arg))

        for app in apps:
            update_contenttypes(app,
                                None,
                                options.get('verbosity', 2),
                                interactive=True)
            create_permissions(app, get_models(), options.get('verbosity', 0))
Exemplo n.º 46
0
    def handle(self, *args, **options):
        if not args:
            apps = []
            for model in get_models():
                try:
                    apps.append(get_app(model._meta.app_label))
                except ImproperlyConfigured:
                    # Ok, the app is not installed, jump to the next app
                    continue
        else:
            apps = []
            for arg in args:
                apps.append(get_app(arg))

        for app in apps:
            create_permissions(app, get_models(), options.get('verbosity', 0))
Exemplo n.º 47
0
def create_user_groups(apps, schema_editor):
    for app_config in apps.get_app_configs():
        app_config.models_module = True
        create_permissions(app_config, verbosity=0)
        app_config.models_module = None

    Group = apps.get_model('auth', 'Group')
    Permission = apps.get_model('auth', 'Permission')
    GROUPS = ['admins', 'editors', 'users']

    for group in GROUPS:
        new_group = Group.objects.create(name=group)
        if group == 'users':
            continue
        model_add_perm = Permission.objects.get(name='Can change publication')
        new_group.permissions.add(model_add_perm)
def generate_permissions(apps, schema_editor):
    Permission = apps.get_model(
        'auth', 'Permission')
    try:
        Permission.objects.get(
            codename='add_post',
            content_type__app_label='blog')
    except Permission.DoesNotExist:
        models_module = getattr(
            apps, 'models_module', None)
        if models_module is None:
            apps.models_module = True
            create_permissions(apps, verbosity=0)
            apps.models_module = None
        else:
            raise
Exemplo n.º 49
0
def create_permissions_compat(app, **kwargs):
    '''
    Creates permissions like syncdb would if we were not using South

    See http://south.aeracode.org/ticket/211
    '''
    from django.db.models import get_app, get_models
    from django.conf import settings
    from django.contrib.auth.management import create_permissions
    if app in ('trans', 'lang', 'accounts'):
        try:
            create_permissions(get_app(app), get_models(),
                               2 if settings.DEBUG else 0)
        except AttributeError as error:
            # See https://code.djangoproject.com/ticket/20442
            print 'Failed to create permission objects: {0}'.format(error)
def update_read_meta_dataset_permissions(apps, schema_editor):
    """Assign the `read_meta_dataset` permission to Datasets
    that existed in the system with the `read_dataset` permission"""

    # Permissions are only created after all migrations are run. Since this
    # data migration needs access to said permissions we manually trigger
    # their creation here.
    apps.models_module = True
    create_permissions(apps, verbosity=0)
    apps.models_module = None

    for dataset in DataSet.objects.all():
        for queryset in [User.objects.all(), Group.objects.all()]:
            for obj in queryset:
                permission_checker = ObjectPermissionChecker(obj)
                if permission_checker.has_perm("core.read_dataset", dataset):
                    assign_perm("core.read_meta_dataset", obj, dataset)
    def forwards(self, orm):
        "Write your forwards methods here."
        # Note: Don't use "from appname.models import ModelName".
        # Use orm.ModelName to refer to models in this application,
        # and orm['appname.ModelName'] for models in other applications.
        update_contenttypes(get_app('notes'), get_models())
        create_permissions(get_app('notes'), get_models(), 0)

        students = orm['auth.Group'].objects.get(name="students")
        students.permissions.add(orm['auth.Permission'].objects.get(content_type__app_label="notes", codename="add_note"))
        students.permissions.add(orm['auth.Permission'].objects.get(content_type__app_label="notes", codename="change_note"))
        students.permissions.add(orm['auth.Permission'].objects.get(content_type__app_label="notes", codename="delete_note"))
        students.save()

        professors = orm['auth.Group'].objects.get(name="professors")
        professors.permissions.add(orm['auth.Permission'].objects.get(content_type__app_label="core", codename="add_course"))
        professors.save()
Exemplo n.º 52
0
def create_group(apps, **_kwargs):
    for app_config in apps.get_app_configs():
        app_config.models_module = True
        create_permissions(app_config, verbosity=0)
        app_config.models_module = None

    add_activity = Permission.objects.get(codename='add_activity')
    change_activity = Permission.objects.get(codename='change_activity')
    delete_activity = Permission.objects.get(codename='delete_activity')

    group, created = Group.objects.get_or_create(name='staff')
    if created:
        group.permissions.add(add_activity, change_activity, delete_activity)

    group, created = Group.objects.get_or_create(name='admin')
    if created:
        group.permissions.add(add_activity, change_activity, delete_activity)
Exemplo n.º 53
0
def create_data(apps, schema_editor):
    for app_config in apps.get_app_configs():
        app_config.models_module = True
        create_permissions(app_config, apps=apps, verbosity=0)
        app_config.models_module = False

    # 添加app
    appname = settings.SAMPLEAPPNAME
    appid = input("please enter your appid: ").strip() or appname
    appsecret = input("please enter your appsecret: ").strip() or "secret"
    app = WeChatApp.objects.create(title="sample app",
                                   name=appname,
                                   appid=appid,
                                   appsecret=appsecret)

    # 增加user
    perm = "{prefix}{appname}".format(prefix=WECHATPERM_PREFIX,
                                      appname=appname)
    if not User.objects.filter(username="******").first():
        User.objects.create_superuser("admin", "", "123456")

    content_type = ContentType.objects.get_for_model(WeChatApp)
    permission = Permission.objects.get(content_type=content_type,
                                        codename=perm)
    try:
        user = User.objects.get(username="******")
    except:
        user = User.objects.create_user("wechat_admin",
                                        "",
                                        "123456",
                                        is_staff=True)

    user.user_permissions.add(permission)
    user.save()

    # 增加一个示例handler
    MessageHandler.objects.create_handler(
        app=app,
        name="debug custom reply",
        flags=MsgLogFlag.LOG_MESSAGE,
        rules=[Rule(type=Rule.Type.CONTAIN, pattern="ab")],
        replies=[
            Reply(type=Reply.MsgType.CUSTOM,
                  program="wechat.views.custom_business"),
            Reply(type=Reply.MsgType.TEXT, content="hello!")
        ])
Exemplo n.º 54
0
    def handle(self, *args, **options):
        if options['apps']:
            app_names = options['apps'].split(',')
            apps = [django_apps.get_app_config(x) for x in app_names]
        else:
            apps = django_apps.get_app_configs()

        if options['create_only']:
            do_create, do_update = True, False
        elif options['update_only']:
            do_create, do_update = False, True
        else:
            do_create, do_update = True, True

        for app in apps:
            if DJANGO_VERSION < (2, 2):
                # see https://github.com/django/django/commit/bec651a427fc032d9115d30c8c5d0e702d754f6c
                # Ensure that contenttypes are created for this app. Needed if
                # 'django.contrib.auth' is in INSTALLED_APPS before
                # 'django.contrib.contenttypes'.
                from django.contrib.contenttypes.management import create_contenttypes
                create_contenttypes(app, verbosity=options['verbosity'])

            if do_create:
                # create permissions if they do not exist
                create_permissions(app, options['verbosity'])

            if do_update:
                # update permission name's if changed
                for model in app.get_models():
                    content_type = ContentType.objects.get_for_model(model)
                    for codename, name in _get_all_permissions(model._meta):
                        try:
                            permission = Permission.objects.get(
                                codename=codename, content_type=content_type)
                        except Permission.DoesNotExist:
                            continue
                        if permission.name != name:
                            old_str = str(permission)
                            permission.name = name
                            if options['verbosity'] >= 2:
                                self.stdout.write(
                                    self.style.SUCCESS(
                                        "Update permission '%s' to '%s'" %
                                        (old_str, permission)))
                            permission.save()
def migrate_up(manager):
    """
    If the auth tables don't exist, we shouldn't try to set the permissions.

    See migration 059
    """
    if db_utils.auth_tables_exist(manager):
        management.setup_environ(settings)
        # These have to be imported after the environment is set up
        from django.contrib.contenttypes import management as content_management
        from django.contrib.auth import management as auth_management
        from django.db import models as db_models

        content_management.update_all_contenttypes()
        for app in db_models.get_apps():
            auth_management.create_permissions(app, None, 2)

        manager.execute_script(migration_059.UP_SQL)
Exemplo n.º 56
0
def add_groups(apps, schema_editor):
    app_config = apps.app_configs['loan_app']
    app_config.models_module = True
    create_permissions(app_config, verbosity=1)
    permission_codename_list = set(
        reduce(lambda acc, el: acc + el, groups.values()))
    Group = apps.get_model('auth', 'Group')
    Permission = apps.get_model('auth', 'Permission')
    permissions_dict = {
        permission_codename:
        Permission.objects.get(codename=permission_codename)
        for permission_codename in permission_codename_list
    }
    for group_name, permission_codenames in groups.items():
        group_object = Group.objects.create(name=group_name)
        for permission_codename in permission_codenames:
            permission = permissions_dict[permission_codename]
            group_object.permissions.add(permission)
Exemplo n.º 57
0
def add_default_member_permission(apps, schema_editor):
    for app_config in apps.get_app_configs():
        app_config.models_module = True
        create_permissions(app_config, apps=apps, verbosity=0)
        app_config.models_module = None

    Group = apps.get_model("auth", "Group")
    Permission = apps.get_model("auth", "Permission")

    try:
        perm = Permission.objects.get(codename='request_groups',
                                      name='Can request non-public groups')
        group = Group.objects.get(
            name=getattr(settings, str('DEFAULT_AUTH_GROUP'), 'Member'))
        group.permissions.add(perm)
    except ObjectDoesNotExist:
        logger.warning(
            'Failed to add default request_groups permission to Member group')
Exemplo n.º 58
0
def permissions(apps, schema_editor):
    try:
        # Django <= 1.10
        from django.contrib.contenttypes.management import update_contenttypes
    except ImportError:
        # Django 1.11 and over
        from django.contrib.contenttypes.management import \
            create_contenttypes as update_contenttypes

    from django.apps import apps as configured_apps
    for app in configured_apps.get_app_configs():
        update_contenttypes(app, interactive=True, verbosity=0)

    from django.contrib.auth.management import create_permissions
    for app in configured_apps.get_app_configs():
        create_permissions(app, verbosity=0)

    create_perms(apps)
Exemplo n.º 59
0
def update_group_permissions(label, group_perms, apps):
    for app_config in apps.get_app_configs():
        app_config.models_module = True
        create_permissions(app_config, apps=apps, verbosity=0)
        app_config.models_module = None

    for group_name, permissions in list(group_perms.items()):
        group, _ = Group.objects.get_or_create(name=group_name)
        for perm_codename in permissions['perms']:
            try:
                permissions = Permission.objects.filter(codename=perm_codename)
                permissions = permissions.filter(content_type__app_label=label)
                group.permissions.add(permissions.get())
            except Permission.DoesNotExist as err:
                logging.debug(err)
                raise Exception('Could not add permission: {}: {}'.format(
                    perm_codename, err))
        group.save()
def insert_permissions_to_employees_group(apps, schema_editor):
    for app_config in apps.get_app_configs():
        app_config.models_module = True
        create_permissions(app_config, verbosity=0)
        app_config.models_module = None

    Customer = apps.get_model('users', 'Customer')
    Group = apps.get_model('auth', 'Group')
    Permission = apps.get_model('auth', 'Permission')
    ContentType = apps.get_model("contenttypes", "ContentType")

    customer_content_type = ContentType.objects.get_for_model(Customer)
    employees_group, _ = Group.objects.get_or_create(name='Employees')
    permission_can_view = Permission.objects.get(
        name='Can view customers',
        codename='can_view',
        content_type=customer_content_type)
    employees_group.permissions.add(permission_can_view)