Python django.contrib.auth.models.Permission() Examples

The following are 30 code examples for showing how to use django.contrib.auth.models.Permission(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.contrib.auth.models , or try the search function .

Example 1
Project: django-river   Author: javrasya   File: config.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def settings(self):
        if self.cached_settings:
            return self.cached_settings
        else:
            from django.conf import settings
            allowed_configurations = {
                'CONTENT_TYPE_CLASS': ContentType,
                'USER_CLASS': settings.AUTH_USER_MODEL,
                'PERMISSION_CLASS': Permission,
                'GROUP_CLASS': Group,
                'INJECT_MODEL_ADMIN': False
            }
            river_settings = {}
            for key, default in allowed_configurations.items():
                river_settings[key] = getattr(settings, self.get_with_prefix(key), default)

            river_settings['IS_MSSQL'] = connection.vendor == 'microsoft'
            self.cached_settings = river_settings

            return self.cached_settings 
Example 2
Project: django-cachalot   Author: noripyt   File: read.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setUp(self):
        super(ReadTestCase, self).setUp()

        self.group = Group.objects.create(name='test_group')
        self.group__permissions = list(Permission.objects.all()[:3])
        self.group.permissions.add(*self.group__permissions)
        self.user = User.objects.create_user('user')
        self.user__permissions = list(Permission.objects.all()[3:6])
        self.user.groups.add(self.group)
        self.user.user_permissions.add(*self.user__permissions)
        self.admin = User.objects.create_superuser('admin', 'admin@test.me',
                                                   'password')
        self.t1__permission = (Permission.objects.order_by('?')
                               .select_related('content_type')[0])
        self.t1 = Test.objects.create(
            name='test1', owner=self.user,
            date='1789-07-14', datetime='1789-07-14T16:43:27',
            permission=self.t1__permission)
        self.t2 = Test.objects.create(
            name='test2', owner=self.admin, public=True,
            date='1944-06-06', datetime='1944-06-06T06:35:00') 
Example 3
Project: django-cachalot   Author: noripyt   File: read.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_filtered_relation(self):
        from django.db.models import FilteredRelation

        qs = TestChild.objects.annotate(
            filtered_permissions=FilteredRelation(
                'permissions', condition=Q(permissions__pk__gt=1)))
        self.assert_tables(qs, TestChild)
        self.assert_query_cached(qs)

        values_qs = qs.values('filtered_permissions')
        self.assert_tables(
            values_qs, TestChild, TestChild.permissions.through, Permission)
        self.assert_query_cached(values_qs)

        filtered_qs = qs.filter(filtered_permissions__pk__gt=2)
        self.assert_tables(
            values_qs, TestChild, TestChild.permissions.through, Permission)
        self.assert_query_cached(filtered_qs) 
Example 4
Project: django-cachalot   Author: noripyt   File: read.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_difference(self):
        qs = Test.objects.filter(pk__lt=5)
        sub_qs = Test.objects.filter(permission__name__contains='a')
        if self.is_sqlite:
            qs = qs.order_by()
            sub_qs = sub_qs.order_by()
        qs = qs.difference(sub_qs)
        self.assert_tables(qs, Test, Permission)
        self.assert_query_cached(qs)

        qs = Test.objects.all()
        sub_qs = Permission.objects.all()
        if self.is_sqlite:
            qs = qs.order_by()
            sub_qs = sub_qs.order_by()
        qs = qs.difference(sub_qs)
        self.assert_tables(qs, Test, Permission)
        with self.assertRaises((ProgrammingError, OperationalError)):
            self.assert_query_cached(qs) 
Example 5
Project: wagtail   Author: wagtail   File: base.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _get_users_with_any_permission_codenames_filter(self, permission_codenames):
        """
        Given a list of permission codenames, return a filter expression which
        will find all users which have any of those permissions - either
        through group permissions, user permissions, or implicitly through
        being a superuser.
        """
        permissions = Permission.objects.filter(
            content_type=self._content_type,
            codename__in=permission_codenames
        )
        return (
            Q(is_superuser=True)
            | Q(user_permissions__in=permissions)
            | Q(groups__permissions__in=permissions)
        ) & Q(is_active=True) 
Example 6
Project: django-protector   Author: grey0ne   File: tests.py    License: MIT License 6 votes vote down vote up
def setUp(self):
        self.TestGroup = get_default_group_ctype().model_class()
        self.user = TestUser.objects.create(username='test1', email='test@test.com')
        self.user2 = TestUser.objects.create(username='test2', email='test2@test.com')
        self.user3 = TestUser.objects.create(username='test3', email='test3@test.com')
        self.responsible_user = TestUser.objects.create_user(username='responsible')
        self.permission = Permission.objects.create(
            codename='test', content_type=get_user_ctype()
        )
        self.permission2 = Permission.objects.create(
            codename='test2', content_type=get_user_ctype()
        )
        self.permission_key = get_user_ctype().app_label + '.test'
        self.permission2_key = get_user_ctype().app_label + '.test2'
        self.group = self.TestGroup.objects.create(
            name='test_group'
        )
        self.group2 = self.TestGroup.objects.create(
            name='test_group2'
        )
        self.group2.restrict()
        self.group2.save()
        self.HistoryOwnerToPermission = HistoryOwnerToPermission
        self.HistoryGenericUserToGroup = HistoryGenericUserToGroup 
Example 7
Project: django-protector   Author: grey0ne   File: models.py    License: MIT License 6 votes vote down vote up
def __unicode__(self):
        if self.object_id is None:
            ctype = None
        else:
            ctype = self.content_type
        result = "{app}.{model}.{pk} ".format(
            app=self.owner_content_type.app_label,
            model=self.owner_content_type.model,
            pk=self.owner_object_id,
        )
        if self.object_id is not None:  # real object not global permission
            result += "- {app}.{model}.{pk}. ".format(
                app=ctype.app_label if ctype else '',
                model=ctype.model if ctype else '',
                pk=self.object_id or '',
            )
        if self.roles:
            result += "Roles {roles}. ".format(roles=self.roles)
        result += "Permission {perm}".format(perm=self.permission.codename)
        return result 
Example 8
Project: kpi   Author: kobotoolbox   File: object_permission.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def _filter_anonymous_perms(self, unfiltered_set):
        """
        Restrict a set of tuples in the format (user_id, permission_id) to
        only those permissions that apply to the content_type of this object
        and are listed in settings.ALLOWED_ANONYMOUS_PERMISSIONS.
        """
        content_type = ContentType.objects.get_for_model(self)
        # Translate settings.ALLOWED_ANONYMOUS_PERMISSIONS to primary keys
        codenames = set()
        for perm in settings.ALLOWED_ANONYMOUS_PERMISSIONS:
            app_label, codename = perm_parse(perm)
            if app_label == content_type.app_label:
                codenames.add(codename)
        allowed_permission_ids = Permission.objects.filter(
            content_type_id=content_type.pk, codename__in=codenames
        ).values_list('pk', flat=True)
        filtered_set = copy.copy(unfiltered_set)
        for user_id, permission_id in unfiltered_set:
            if user_id == settings.ANONYMOUS_USER_ID:
                if permission_id not in allowed_permission_ids:
                    filtered_set.remove((user_id, permission_id))
        return filtered_set 
Example 9
Project: kpi   Author: kobotoolbox   File: object_permission.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def get_users_with_perms(self, attach_perms=False):
        """ Return a QuerySet of all users with any effective grant permission
        on this object. If attach_perms=True, then return a dict with
        users as the keys and lists of their permissions as the values. """
        user_perm_ids = self._get_effective_perms()
        if attach_perms:
            user_perm_dict = {}
            for user_id, perm_id in user_perm_ids:
                perm_list = user_perm_dict.get(user_id, [])
                perm_list.append(Permission.objects.get(pk=perm_id).codename)
                user_perm_dict[user_id] = sorted(perm_list)
            # Resolve user ids into actual user objects
            user_perm_dict = {User.objects.get(pk=key): value for key, value
                              in user_perm_dict.items()}
            return user_perm_dict
        else:
            # Use a set to avoid duplicate users
            user_ids = {x[0] for x in user_perm_ids}
            return User.objects.filter(pk__in=user_ids) 
Example 10
Project: django-organice   Author: Organice   File: permissions.py    License: Apache License 2.0 6 votes vote down vote up
def reset_group_permissions(group_name, app_permissions=(), cms_permissions=(), sites=()):
    """
    Initialize a Django auth group assigning a set of Django app permissions,
    and global page permissions for django CMS.

    :param group_name: Name of Django auth group to create or reset
    :param app_permissions: list of Django auth Permission objects
    :param cms_permissions: dictionary of django CMS permissions
    :param sites: optional list of Django sites objects (None: all sites)
    :return: the created or updated group model instance
    """
    group, created = Group.objects.get_or_create(name=group_name)
    group.permissions = permission_list(app_permissions)
    group.save()

    perms, created = GlobalPagePermission.objects.get_or_create(group=group)
    for attrib, value in dict(cms_permissions).items():
        setattr(perms, attrib, value)
    perms.sites = sites
    perms.save()

    return group 
Example 11
Project: Kiwi   Author: kiwitcms   File: __init__.py    License: GNU General Public License v2.0 6 votes vote down vote up
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') 
Example 12
Project: djongo   Author: nesdis   File: test_management.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_default_permissions(self):
        permission_content_type = ContentType.objects.get_by_natural_key('auth', 'permission')
        Permission._meta.permissions = [
            ('my_custom_permission', 'Some permission'),
        ]
        create_permissions(self.app_config, verbosity=0)

        # view/add/change/delete permission by default + custom permission
        self.assertEqual(Permission.objects.filter(
            content_type=permission_content_type,
        ).count(), 5)

        Permission.objects.filter(content_type=permission_content_type).delete()
        Permission._meta.default_permissions = []
        create_permissions(self.app_config, verbosity=0)

        # custom permission only since default permissions is empty
        self.assertEqual(Permission.objects.filter(
            content_type=permission_content_type,
        ).count(), 1) 
Example 13
Project: djongo   Author: nesdis   File: test_management.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_default_permissions(self):
        permission_content_type = ContentType.objects.get_by_natural_key('auth', 'permission')
        Permission._meta.permissions = [
            ('my_custom_permission', 'Some permission'),
        ]
        create_permissions(self.app_config, verbosity=0)

        # view/add/change/delete permission by default + custom permission
        self.assertEqual(Permission.objects.filter(
            content_type=permission_content_type,
        ).count(), 5)

        Permission.objects.filter(content_type=permission_content_type).delete()
        Permission._meta.default_permissions = []
        create_permissions(self.app_config, verbosity=0)

        # custom permission only since default permissions is empty
        self.assertEqual(Permission.objects.filter(
            content_type=permission_content_type,
        ).count(), 1) 
Example 14
Project: connect   Author: ofa   File: views.py    License: MIT License 6 votes vote down vote up
def get_editable_permissions(self):
        """
        Return a queryset of Permission objects that can be assigned

        The view has an attribute called `editable_permissions` but that
        attribute only lists app names and permission codenames. We need to
        turn that tuple of tuples into a queryset of permissions.
        """
        # Dynamic generation of OR queries is based on code found at
        # https://bradmontgomery.net/blog/adding-q-objects-in-django/
        permission_filter = Q()
        for permission in self.editable_permissions:
            permission_filter.add(
                Q(content_type__app_label=permission[0],
                  codename=permission[1]), Q.OR)

        return Permission.objects.filter(
            permission_filter) 
Example 15
Project: connect   Author: ofa   File: views.py    License: MIT License 6 votes vote down vote up
def get_permissions_queryset(self):
        """
        Get the queryset to pre-fill the optional individual permission list

        There are a significant number of possible permissions within every
        django app. Most of these permissions are not necessary for the
        operation of the app, so we never display more than the ones required.

        However, due to the way that UpdateViews and Many-to-Many forms are
        saved when a form with a many-to-many field is submitted all existing
        relationships are cleared and replaced with those submitted.

        If, by some chance, a user has an individual permission that is not
        listed above, the easiest way to handle this is to simply append the
        permission to the form in order to prevent data corruption.
        """
        editable_permissions_queryset = self.get_editable_permissions()
        existing_permissions_queryset = self.object.user_permissions.all()

        return Permission.objects.filter(
            Q(pk__in=editable_permissions_queryset.values('pk')) |
            Q(pk__in=existing_permissions_queryset.values('pk'))
            ).order_by('content_type__app_label').select_related('content_type') 
Example 16
Project: connect   Author: ofa   File: test_views.py    License: MIT License 6 votes vote down vote up
def setUp(self):
        """Handy things."""
        self.request_factory = RequestFactory()

        # Add 2 permissions to the test, one valid and visible, one hidden
        demo_content_type = ContentType.objects.create(
            app_label='demo-app-label', model='DemoModel')

        self.valid_permission = mommy.make(
            Permission,
            codename='viewable-permission',
            name='Viewable Permission',
            content_type=demo_content_type)
        self.hidden_permission = mommy.make(
            Permission,
            codename='hidden-permission',
            name='Hidden Permission',
            content_type=demo_content_type)

        # Create a view class that contains those permissions
        self.view_class = views.UpdateUserPermissionView
        self.view_class.editable_permissions = (
            ('demo-app-label', 'viewable-permission'),
        ) 
Example 17
Project: tethys   Author: tethysplatform   File: test_admin.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def setUp(self):
        from tethys_apps.models import TethysApp
        self.src_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
        self.root_app_path = os.path.join(self.src_dir, 'apps', 'tethysapp-test_app')
        self.app_model = TethysApp(
            name='test_app',
            package='test_app'
        )
        self.app_model.save()

        from django.contrib.auth.models import ContentType, Group, Permission

        app_content_type_id = ContentType.objects.get(app_label='tethys_apps', model='tethysapp').pk
        self.perm_model = Permission(
            name='Test Perm | Test',
            content_type_id=app_content_type_id,
            codename='test_perm:test'
        )
        self.perm_model.save()

        self.group_model = Group(
            name='test_group'
        )
        self.group_model.save() 
Example 18
Project: donation-tracker   Author: GamesDoneQuick   File: test_me.py    License: Apache License 2.0 5 votes vote down vote up
def test_user_with_permissions(self):
        self.request.user.user_permissions.add(
            Permission.objects.get(codename='add_user')
        )
        self.assertEqual(
            self.parseJSON(tracker.views.me(self.request)),
            {'username': 'test', 'permissions': ['auth.add_user']},
        ) 
Example 19
Project: donation-tracker   Author: GamesDoneQuick   File: test_me.py    License: Apache License 2.0 5 votes vote down vote up
def test_user_with_group_permissions(self):
        group = Group.objects.create(name='Test Group')
        group.permissions.add(Permission.objects.get(codename='add_user'))
        group.user_set.add(self.request.user)
        self.assertEqual(
            self.parseJSON(tracker.views.me(self.request)),
            {'username': 'test', 'permissions': ['auth.add_user']},
        ) 
Example 20
Project: donation-tracker   Author: GamesDoneQuick   File: test_me.py    License: Apache License 2.0 5 votes vote down vote up
def test_anonymous_user(self):
        self.request.user = AnonymousUser()
        self.assertEqual(
            self.parseJSON(tracker.views.me(self.request), 403),
            {'error': 'Permission Denied', 'exception': '',},
        ) 
Example 21
Project: resolwe   Author: genialis   File: shortcuts.py    License: Apache License 2.0 5 votes vote down vote up
def get_users_with_permission(obj, permission):
    """Return users with specific permission on object.

    :param obj: Object to return users for
    :param permission: Permission codename
    """
    user_model = get_user_model()
    return user_model.objects.filter(
        userobjectpermission__object_pk=obj.pk,
        userobjectpermission__permission__codename=permission,
    ).distinct() 
Example 22
Project: kobo-predict   Author: awemulya   File: test_team.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
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) 
Example 23
Project: django-cachalot   Author: noripyt   File: read.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_distinct(self):
        # We ensure that the query without distinct should return duplicate
        # objects, in order to have a real-world example.
        qs = Test.objects.filter(
            owner__user_permissions__content_type__app_label='auth')
        self.assert_tables(qs, Test, User, User.user_permissions.through,
                           Permission, ContentType)
        self.assert_query_cached(qs, [self.t1, self.t1, self.t1])

        qs = qs.distinct()
        self.assert_tables(qs, Test, User, User.user_permissions.through,
                           Permission, ContentType)
        self.assert_query_cached(qs, [self.t1]) 
Example 24
Project: django-cachalot   Author: noripyt   File: read.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_many_to_many(self):
        u = User.objects.create_user('test_user')
        ct = ContentType.objects.get_for_model(User)
        u.user_permissions.add(
            Permission.objects.create(
                name='Can discuss', content_type=ct, codename='discuss'),
            Permission.objects.create(
                name='Can touch', content_type=ct, codename='touch'),
            Permission.objects.create(
                name='Can cuddle', content_type=ct, codename='cuddle'))
        qs = u.user_permissions.values_list('codename', flat=True)
        self.assert_tables(qs, User, User.user_permissions.through, Permission)
        self.assert_query_cached(qs, ['cuddle', 'discuss', 'touch']) 
Example 25
Project: django-cachalot   Author: noripyt   File: read.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_subquery(self):
        qs = Test.objects.filter(owner__in=User.objects.all())
        self.assert_tables(qs, Test, User)
        self.assert_query_cached(qs, [self.t1, self.t2])

        qs = Test.objects.filter(
            owner__groups__permissions__in=Permission.objects.all())
        self.assert_tables(qs, Test, User, User.groups.through, Group,
                           Group.permissions.through, Permission)
        self.assert_query_cached(qs, [self.t1, self.t1, self.t1])

        qs = Test.objects.filter(
            owner__groups__permissions__in=Permission.objects.all()
        ).distinct()
        self.assert_tables(qs, Test, User, User.groups.through, Group,
                           Group.permissions.through, Permission)
        self.assert_query_cached(qs, [self.t1])

        qs = TestChild.objects.exclude(permissions__isnull=True)
        self.assert_tables(qs, TestParent, TestChild,
                           TestChild.permissions.through, Permission)
        self.assert_query_cached(qs, [])

        qs = TestChild.objects.exclude(permissions__name='')
        self.assert_tables(qs, TestParent, TestChild,
                           TestChild.permissions.through, Permission)
        self.assert_query_cached(qs, []) 
Example 26
Project: django-cachalot   Author: noripyt   File: read.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_custom_subquery(self):
        tests = Test.objects.filter(permission=OuterRef('pk')).values('name')
        qs = Permission.objects.annotate(first_permission=Subquery(tests[:1]))
        self.assert_tables(qs, Permission, Test)
        self.assert_query_cached(qs, list(Permission.objects.all())) 
Example 27
Project: django-cachalot   Author: noripyt   File: read.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_raw_subquery(self):
        with self.assertNumQueries(0):
            raw_sql = RawSQL('SELECT id FROM auth_permission WHERE id = %s',
                             (self.t1__permission.pk,))
        qs = Test.objects.filter(permission=raw_sql)
        self.assert_tables(qs, Test, Permission)
        self.assert_query_cached(qs, [self.t1])

        qs = Test.objects.filter(
            pk__in=Test.objects.filter(permission=raw_sql))
        self.assert_tables(qs, Test, Permission)
        self.assert_query_cached(qs, [self.t1]) 
Example 28
Project: django-cachalot   Author: noripyt   File: read.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_union(self):
        qs = (Test.objects.filter(pk__lt=5)
              | Test.objects.filter(permission__name__contains='a'))
        self.assert_tables(qs, Test, Permission)
        self.assert_query_cached(qs)

        with self.assertRaisesMessage(
                AssertionError,
                'Cannot combine queries on two different base models.'):
            Test.objects.all() | Permission.objects.all()

        qs = Test.objects.filter(pk__lt=5)
        sub_qs = Test.objects.filter(permission__name__contains='a')
        if self.is_sqlite:
            qs = qs.order_by()
            sub_qs = sub_qs.order_by()
        qs = qs.union(sub_qs)
        self.assert_tables(qs, Test, Permission)
        self.assert_query_cached(qs)

        qs = Test.objects.all()
        sub_qs = Permission.objects.all()
        if self.is_sqlite:
            qs = qs.order_by()
            sub_qs = sub_qs.order_by()
        qs = qs.union(sub_qs)
        self.assert_tables(qs, Test, Permission)
        with self.assertRaises((ProgrammingError, OperationalError)):
            self.assert_query_cached(qs) 
Example 29
Project: django-cachalot   Author: noripyt   File: read.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_intersection(self):
        qs = (Test.objects.filter(pk__lt=5)
              & Test.objects.filter(permission__name__contains='a'))
        self.assert_tables(qs, Test, Permission)
        self.assert_query_cached(qs)

        with self.assertRaisesMessage(
                AssertionError,
                'Cannot combine queries on two different base models.'):
            Test.objects.all() & Permission.objects.all()

        qs = Test.objects.filter(pk__lt=5)
        sub_qs = Test.objects.filter(permission__name__contains='a')
        if self.is_sqlite:
            qs = qs.order_by()
            sub_qs = sub_qs.order_by()
        qs = qs.intersection(sub_qs)
        self.assert_tables(qs, Test, Permission)
        self.assert_query_cached(qs)

        qs = Test.objects.all()
        sub_qs = Permission.objects.all()
        if self.is_sqlite:
            qs = qs.order_by()
            sub_qs = sub_qs.order_by()
        qs = qs.intersection(sub_qs)
        self.assert_tables(qs, Test, Permission)
        with self.assertRaises((ProgrammingError, OperationalError)):
            self.assert_query_cached(qs) 
Example 30
Project: waliki   Author: mgaitan   File: factories.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def permissions(self, create, extracted, **kwargs):
        if not create:
            # Simple build, do nothing.
            return

        if extracted:
            # A list of groups were passed in, use them
            for perm in extracted:
                if not isinstance(perm, Permission):
                    perm = Permission.objects.get(content_type__app_label='waliki', codename=perm)
                self.permissions.add(perm)