Python django.contrib.auth.models 模块,Permission() 实例源码

我们从Python开源项目中,提取了以下29个代码示例,用于说明如何使用django.contrib.auth.models.Permission()

项目:django-chemtrails    作者:inonit    | 项目源码 | 文件源码
def test_get_all_permissions_mixed_user_and_group(self):
        permissions = Permission.objects.filter(content_type__app_label='auth',
                                                codename__in=[
                                                    'add_user', 'change_user',
                                                    'add_group', 'change_group'
                                                ])
        user = User.objects.create_user(username='testuser', password='test123.')
        group = Group.objects.create(name='group')
        group.user_set.add(user)

        user.user_permissions.add(*permissions.filter(content_type__model='user'))
        group.permissions.add(*permissions.filter(content_type__model='group'))

        backend = ChemoPermissionsBackend()

        self.assertEqual(
            set(permissions.filter(content_type__model='group').values_list('codename', flat=True)),
            set(backend.get_all_permissions(user, group))
        )
        self.assertEqual(
            set(permissions.filter(content_type__model='user').values_list('codename', flat=True)),
            set(backend.get_all_permissions(user, user))
        )
项目:django-chemtrails    作者:inonit    | 项目源码 | 文件源码
def test_user_has_perm_multiple_relation_types(self):
        # Set up a bookstore graph
        store = StoreFixture(Store).create_one()
        get_nodeset_for_queryset(Store.objects.filter(pk=store.pk), sync=True)
        permissions = Permission.objects.filter(codename__in=['add_store', 'change_store', 'delete_store'])

        user = get_user_model().objects.latest('pk')
        user.user_permissions.add(*list(permissions))

        # Create an access rule which allows 'add_store' and 'change_store',
        # but not 'delete_store'
        access_rule = AccessRule.objects.create(
            ctype_source=ContentType.objects.get_for_model(user),
            ctype_target=ContentType.objects.get_for_model(Store),
            relation_types=[{'AUTHOR': None}, {'BOOK': None}, {'STORE': None}]
        )
        access_rule.permissions.add(*list(permissions.exclude(codename='delete_store')))

        self.assertTrue(user.has_perm('testapp.add_store', store))
        self.assertTrue(user.has_perm('testapp.change_store', store))
        self.assertFalse(user.has_perm('testapp.delete_store', store))
项目:django-chemtrails    作者:inonit    | 项目源码 | 文件源码
def test_get_all_permissions_user(self):
        permissions = Permission.objects.filter(content_type__app_label='auth',
                                                codename__in=[
                                                    'add_user', 'change_user',
                                                    'add_group', 'change_group'
                                                ])
        user = User.objects.create_user(username='testuser', password='test123.')
        group = Group.objects.create(name='group')
        user.user_permissions.add(*permissions)

        backend = ChemoPermissionsBackend()

        self.assertEqual(
            set(permissions.filter(content_type__model='group').values_list('codename', flat=True)),
            set(backend.get_all_permissions(user, group))
        )
        self.assertEqual(
            set(permissions.filter(content_type__model='user').values_list('codename', flat=True)),
            set(backend.get_all_permissions(user, user))
        )
项目:django-chemtrails    作者:inonit    | 项目源码 | 文件源码
def test_get_all_permissions_group(self):
        permissions = Permission.objects.filter(content_type__app_label='auth',
                                                codename__in=[
                                                    'add_user', 'change_user',
                                                    'add_group', 'change_group'
                                                ])
        user = User.objects.create_user(username='testuser', password='test123.')
        group = Group.objects.create(name='group')
        group.user_set.add(user)
        group.permissions.add(*permissions)

        backend = ChemoPermissionsBackend()

        self.assertEqual(
            set(permissions.filter(content_type__model='group').values_list('codename', flat=True)),
            set(backend.get_all_permissions(user, group))
        )
        self.assertEqual(
            set(permissions.filter(content_type__model='user').values_list('codename', flat=True)),
            set(backend.get_all_permissions(user, user))
        )
项目:Kiwi    作者:kiwitcms    | 项目源码 | 文件源码
def user_should_have_perm(user, perm):
    if isinstance(perm, str):
        try:
            app_label, codename = perm.split('.')
        except ValueError:
            raise ValueError('%s is not valid. Should be in format app_label.perm_codename')
        else:
            if not app_label or not codename:
                raise ValueError('Invalid app_label or codename')
            get_permission = Permission.objects.get
            user.user_permissions.add(
                get_permission(content_type__app_label=app_label, codename=codename))
    elif isinstance(perm, Permission):
        user.user_permissions.add(perm)
    else:
        raise TypeError('perm should be an instance of either str or Permission')
项目:Kiwi    作者:kiwitcms    | 项目源码 | 文件源码
def remove_perm_from_user(user, perm):
    """Remove a permission from an user"""

    if isinstance(perm, str):
        try:
            app_label, codename = perm.split('.')
        except ValueError:
            raise ValueError('%s is not valid. Should be in format app_label.perm_codename')
        else:
            if not app_label or not codename:
                raise ValueError('Invalid app_label or codename')
            get_permission = Permission.objects.get
            user.user_permissions.remove(
                get_permission(content_type__app_label=app_label, codename=codename))
    elif isinstance(perm, Permission):
        user.user_permissions.remove(perm)
    else:
        raise TypeError('perm should be an instance of either str or Permission')
项目:tecken    作者:mozilla-services    | 项目源码 | 文件源码
def drop_permissions_on_group_change(sender, instance, action, **kwargs):
    if action == 'post_remove':
        # A permission was removed from a group.
        # Every Token that had this permission needs to be re-evaluated
        # because, had the user created this token now, they might
        # no longer have access to that permission due to their
        # group memberships.
        permissions = Permission.objects.filter(id__in=kwargs['pk_set'])
        for permission in permissions:
            for token in Token.objects.filter(permissions=permission):
                user_permissions = Permission.objects.filter(
                    group__user=token.user
                )
                if permission not in user_permissions:
                    token.permissions.remove(permission)
项目:django-audit-tools    作者:PeRDy    | 项目源码 | 文件源码
def register_permissions():
    """
    Method to register permissions in database
    """
    try:
        content_type, ct_created = ContentType.objects.get_or_create(
            app_label='audit',
            name='audit',
            model='audit'
        )
        if not ct_created:
            logger.warn('Content type registered yet: audit')

        for permission_code, permission_name in AUDIT_PERMISSIONS:
            permission, permission_created = Permission.objects.get_or_create(
                content_type=content_type,
                codename=permission_code,
                name=permission_name
            )
            if not permission_created:
                logger.warn('Permission registered yet: {}'.format(permission_code))
    except Exception:
        logger.exception("Error registering permissions")
        return False

    logger.info("Audit registered properly")

    return True
项目:django-audit-tools    作者:PeRDy    | 项目源码 | 文件源码
def unregister_permissions():
    """
    Method to unregister permissions in database
    """
    try:
        content_type = ContentType.objects.get(app_label='audit', name='audit', model='audit')
        Permission.objects.filter(content_type=content_type).delete()
        ContentType.objects.filter(app_label='audit', name='audit', model='audit').delete()
    except ContentType.DoesNotExist:
        logger.exception("Audit isn't registered")
        return False

    logger.info("Audit unregistered properly")
    return True
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def test_create_organization_team(self):
        profile = tools.create_organization("modilabs", self.user)
        organization = profile.user
        team_name = 'dev'
        perms = ['is_org_owner', ]
        tools.create_organization_team(organization, team_name, perms)
        team_name = "modilabs#%s" % team_name
        dev_team = Team.objects.get(organization=organization, name=team_name)

        self.assertIsInstance(dev_team, Team)
        self.assertIsInstance(
            dev_team.permissions.get(codename='is_org_owner'), Permission)
项目:django-chemtrails    作者:inonit    | 项目源码 | 文件源码
def test_create_model_with_content_types(self):
        permission = Permission.objects.latest('pk')

        @six.add_metaclass(ModelNodeMeta)
        class ModelNode(ModelNodeMixin, StructuredNode):
            class Meta:
                model = Permission

        self.assertTrue(issubclass(ModelNode, StructuredNode))
        self.assertIsInstance(ModelNode(instance=permission), StructuredNode)
项目:django-chemtrails    作者:inonit    | 项目源码 | 文件源码
def test_ignored_models_app_label_model_name(self):
        klass = get_node_class_for_model(Group)
        self.assertTrue(klass._is_ignored)

        klass = get_node_class_for_model(Permission)
        self.assertFalse(klass._is_ignored)
项目:django-chemtrails    作者:inonit    | 项目源码 | 文件源码
def test_user_has_perm_single_relation_type(self):
        author = AuthorFixture(Author).create_one()
        permission = Permission.objects.get(codename='change_author')
        author.user.user_permissions.add(permission)
        access_rule = AccessRule.objects.create(
            ctype_source=ContentType.objects.get_for_model(author.user),
            ctype_target=ContentType.objects.get_for_model(author),
            relation_types=[{'AUTHOR': None}]
        )
        access_rule.permissions.add(permission)
        self.assertTrue(author.user.has_perm('testapp.change_author', author))
项目:DjangoCMS    作者:farhan711    | 项目源码 | 文件源码
def assign_perm(self, perm, user, obj):
        """
        Assigns permission with given ``perm`` for an instance ``obj`` and
        ``user``.
        """
        if getattr(obj, 'pk', None) is None:
            raise Exception("Object %s needs to be persisted first" % obj)
        ctype = ContentType.objects.get_for_model(obj)
        permission = Permission.objects.get(content_type=ctype, codename=perm)

        kwargs = {'permission': permission, 'user': user}
        kwargs['content_type'] = ctype
        kwargs['object_pk'] = obj.pk
        obj_perm, created = self.get_or_create(**kwargs)  # @UnusedVariable
        return obj_perm
项目:DjangoCMS    作者:farhan711    | 项目源码 | 文件源码
def test_authed_basic_perm(self):
        self.user.user_permissions.add(Permission.objects.get(codename='view_page'))
        request = self.get_request(self.user)
        with self.assertNumQueries(5):
            """
            The queries are:
            Site
            PagePermission count query
            GlobalpagePermission count query
            User permissions
            Content type
            """
            result = get_visible_pages(request, self.pages, self.page.site)
            self.assertEqual(result, [self.page.pk])
项目:DjangoCMS    作者:farhan711    | 项目源码 | 文件源码
def test_authed_no_access(self):
        request = self.get_request(self.user)
        with self.assertNumQueries(5):
            """
            The queries are:
            Site
            View Permission Calculation Query
            GlobalpagePermission query for user
            User permissions
            Content type
            """
            result = get_visible_pages(request, self.pages, self.page.site)
            self.assertEqual(result, [])
项目:django-north    作者:peopledoc    | 项目源码 | 文件源码
def test_missing_permissions(mocker):
    ct1 = ContentType(app_label='myapp1', model='mymodel1', id=1)
    ct2 = ContentType(app_label='myapp1', model='mymodel2', id=2)
    p1 = Permission(codename='perm1', name='Perm1', content_type=ct1)
    p2 = Permission(codename='perm2', name='Perm2', content_type=ct1)
    p3 = Permission(codename='perm3', name='Perm3', content_type=ct2)
    app_config1 = CustomAppConfig('myapp1', mocker.Mock())
    app_config2 = CustomAppConfig('myapp2', mocker.Mock())
    app_config3 = CustomAppConfig('myapp3', mocker.Mock())
    mocker.patch(
        'django_north.management.commands.showfixtures.apps'
        '.get_app_configs',
        return_value=[app_config1, app_config2, app_config3])
    mock_get_permissions = mocker.patch(
        'django_north.management.permissions'
        '.get_missing_permissions_for_app_config')

    command = showfixtures.Command()

    # missing permissions
    mock_get_permissions.side_effect = [
        [p1, p2],
        [p3],
        []]
    assert command.missing_permissions() == [
        "INSERT INTO auth_permission(codename, name, content_type_id) "
        "VALUES('perm1', 'Perm1', (SELECT id FROM django_content_type "
        "WHERE app_label = 'myapp1' AND model = 'mymodel1'));",
        "INSERT INTO auth_permission(codename, name, content_type_id) "
        "VALUES('perm2', 'Perm2', (SELECT id FROM django_content_type "
        "WHERE app_label = 'myapp1' AND model = 'mymodel1'));",
        "INSERT INTO auth_permission(codename, name, content_type_id) "
        "VALUES('perm3', 'Perm3', (SELECT id FROM django_content_type "
        "WHERE app_label = 'myapp1' AND model = 'mymodel2'));",
    ]

    # no missing permissions
    mock_get_permissions.side_effect = [[], [], []]
    assert command.missing_permissions() == []
项目:omni-forms    作者:omni-digital    | 项目源码 | 文件源码
def setUp(self):
        super(OmniManyToManyFieldTestCase, self).setUp()
        self.field = OmniManyToManyField(
            related_type=ContentType.objects.get_for_model(Permission),
            name='Test Field',
            label='Test Field Label',
            help_text='Test help text',
            required=True,
            widget_class=OmniManyToManyField.FORM_WIDGETS[0],
            form=self.omni_form
        )
        self.field.save()
项目:omni-forms    作者:omni-digital    | 项目源码 | 文件源码
def test_as_form_field(self):
        """
        The as_form_field method should set the queryset
        """
        field_class = import_string(self.field.FIELD_CLASS)
        widget_class = import_string(self.field.widget_class)
        instance = self.field.as_form_field()
        self.assertIsInstance(instance, field_class)
        self.assertEqual(self.field.label, instance.label)
        self.assertEqual(self.field.help_text, instance.help_text)
        self.assertTrue(self.field.required)
        self.assertIsInstance(instance.widget, widget_class)
        self.assertEquals(list(instance.queryset), list(Permission.objects.all()))
项目:omni-forms    作者:omni-digital    | 项目源码 | 文件源码
def setUp(self):
        super(OmniForeignKeyFieldTestCase, self).setUp()
        self.field = OmniForeignKeyField(
            related_type=ContentType.objects.get_for_model(Permission),
            name='Test Field',
            label='Test Field Label',
            help_text='Test help text',
            required=True,
            widget_class=OmniForeignKeyField.FORM_WIDGETS[0],
            form=self.omni_form
        )
        self.field.save()
项目:omni-forms    作者:omni-digital    | 项目源码 | 文件源码
def test_as_form_field(self):
        """
        The as_form_field method should set the queryset
        """
        field_class = import_string(self.field.FIELD_CLASS)
        widget_class = import_string(self.field.widget_class)
        instance = self.field.as_form_field()
        self.assertIsInstance(instance, field_class)
        self.assertEqual(self.field.label, instance.label)
        self.assertEqual(self.field.help_text, instance.help_text)
        self.assertTrue(self.field.required)
        self.assertIsInstance(instance.widget, widget_class)
        self.assertEquals(list(instance.queryset), list(Permission.objects.all()))
项目:wagtailtrans    作者:LUKKIEN    | 项目源码 | 文件源码
def create_group_permissions(group, language):
    """create all required permissions on the translator group

    :param group:  Group instance
    :param language: Language instance
    """
    collection_perms = [
        Permission.objects.get_by_natural_key(
            u'add_document', u'wagtaildocs', u'document'),
        Permission.objects.get_by_natural_key(
            u'change_document', u'wagtaildocs', u'document'),
        Permission.objects.get_by_natural_key(
            u'delete_document', u'wagtaildocs', u'document'),
        Permission.objects.get_by_natural_key(
            u'change_image', u'wagtailimages', u'image'),
        Permission.objects.get_by_natural_key(
            u'add_image', u'wagtailimages', u'image'),
        Permission.objects.get_by_natural_key(
            u'delete_image', u'wagtailimages', u'image'),
    ]
    # access wagtail admin permission
    group.permissions.add(Permission.objects.get_by_natural_key(
        u'access_admin', u'wagtailadmin', u'admin'
    ))

    collection = Collection.objects.filter(
        name='collection-%s' % language.code).first()
    if not collection:
        root = Collection.objects.first().get_root()
        collection = root.add_child(name='collection-%s' % language.code)
        for perm in collection_perms:
            GroupCollectionPermission.objects.create(
                permission=perm,
                group=group,
                collection=collection
            )
项目:wagtailtrans    作者:LUKKIEN    | 项目源码 | 文件源码
def for_page(self, page):
        """Get the user page permissions for this page
        We implement our custom  Permission tester here

        :param page: Page object
        :return: TranslatablePagePermissionsTester instance

        """
        return TranslatablePagePermissionTester(self, page)
项目:tissuelab    作者:VirtualPlants    | 项目源码 | 文件源码
def test_perms_attrs(self):
        u = User.objects.create_user(username='normal', password='secret')
        u.user_permissions.add(
            Permission.objects.get(
                content_type=ContentType.objects.get_for_model(Permission),
                codename='add_permission'))
        self.client.login(username='normal', password='secret')
        response = self.client.get('/auth_processor_perms/')
        self.assertContains(response, "Has auth permissions")
        self.assertContains(response, "Has auth.add_permission permissions")
        self.assertNotContains(response, "nonexisting")
项目:tissuelab    作者:VirtualPlants    | 项目源码 | 文件源码
def test_perm_in_perms_attrs(self):
        u = User.objects.create_user(username='normal', password='secret')
        u.user_permissions.add(
            Permission.objects.get(
                content_type=ContentType.objects.get_for_model(Permission),
                codename='add_permission'))
        self.client.login(username='normal', password='secret')
        response = self.client.get('/auth_processor_perm_in_perms/')
        self.assertContains(response, "Has auth permissions")
        self.assertContains(response, "Has auth.add_permission permissions")
        self.assertNotContains(response, "nonexisting")
项目:django-boardinghouse    作者:schinckel    | 项目源码 | 文件源码
def test_contrib_models(self):
        from django.contrib.admin.models import LogEntry
        from django.contrib.auth.models import User, Group, Permission

        self.assertTrue(is_shared_model(User()))
        self.assertTrue(is_shared_model(Permission()))
        self.assertTrue(is_shared_model(Group()))
        self.assertTrue(is_shared_model(LogEntry()))
项目:FormShare    作者:qlands    | 项目源码 | 文件源码
def test_create_organization_team(self):
        profile = tools.create_organization("modilabs", self.user)
        organization = profile.user
        team_name = 'dev'
        perms = ['is_org_owner', ]
        tools.create_organization_team(organization, team_name, perms)
        team_name = "modilabs#%s" % team_name
        dev_team = Team.objects.get(organization=organization, name=team_name)

        self.assertIsInstance(dev_team, Team)
        self.assertIsInstance(
            dev_team.permissions.get(codename='is_org_owner'), Permission)
项目:zing    作者:evernote    | 项目源码 | 文件源码
def create_pootle_permissions(self):
        """Create Pootle's directory level permissions."""

        args = {
            'app_label': "pootle_app",
            'model': "directory",
        }

        pootle_content_type = self._create_object(ContentType, **args)[0]
        pootle_content_type.save()

        # Create the permissions.
        permissions = [
            {
                'name': _("Can access a project"),
                'codename': "view",
            },
            {
                'name': _("Cannot access a project"),
                'codename': "hide",
            },
            {
                'name': _("Can make a suggestion for a translation"),
                'codename': "suggest",
            },
            {
                'name': _("Can submit a translation"),
                'codename': "translate",
            },
            {
                'name': _("Can review suggestions"),
                'codename': "review",
            },
            {
                'name': _("Can perform administrative tasks"),
                'codename': "administrate",
            },
        ]

        criteria = {
            'content_type': pootle_content_type,
        }

        for permission in permissions:
            criteria.update(permission)
            self._create_object(Permission, **criteria)
项目:django-dex    作者:synw    | 项目源码 | 文件源码
def clone(self, dbsource, dbdest, applist=None, verbosity=1):
        global EXCLUDE
        st = time.time()
        if applist is None:
            applist = settings.INSTALLED_APPS
        source = self._get_django_db(dbsource)
        if source is None:
            msg = "Database", dbsource, "not found"
            err.new(self.clone, msg)
            return
        dest = self._get_django_db(dbdest)
        if dest is None:
            msg = "Database", dbdest, "not found"
            err.new(self.clone, msg)
            return
        if verbosity > 0:
            print("Cloning database", dbsource, "in database", dbdest)
        models = {}
        for appname in applist:
            appstr = appname.split('.')[-1]
            if appstr in EXCLUDE or appstr.startswith("django.") \
                    or appstr == "django.contrib.contenttypes":
                continue
            # remove all remaining dots to keep just the app name
            try:
                s = appname.split(".")
                appname = s[len(s) - 1]
            except:
                pass
            models[appname] = inspect.models(appname)
        num_models = 0
        num_instances = 0
        stats = {}
        appname = "contenttypes"
        if verbosity > 0:
            print("Found", str(len(applist)), "applications")
        for appname in models:
            if appname == "contenttypes" or appname == "sessions":
                continue
            else:
                if len(models[appname]) > 0:
                    print("# Processing app", appname)
                    stats[appname] = {}
                    stats[appname]["num_models"] = 0
                    for model in models[appname]:
                        if model == Permission or model == Site:
                            continue
                        num_models += 1
                        stats, num_instances = self.clone_model(model, dbsource, dbdest,
                                                                num_instances, appname,
                                                                models, num_models, stats, verbosity)
                        err.fatal()
        self.stats(models, stats, num_models, num_instances, st)