Python django.contrib.auth.models.Permission() Examples
The following are 30
code examples of django.contrib.auth.models.Permission().
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 also want to check out all available functions/classes of the module
django.contrib.auth.models
, or try the search function
.
Example #1
Source File: __init__.py From Kiwi with GNU General Public License v2.0 | 6 votes |
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 #2
Source File: read.py From django-cachalot with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Source File: test_views.py From connect with MIT License | 6 votes |
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 #4
Source File: test_admin.py From tethys with BSD 2-Clause "Simplified" License | 6 votes |
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 #5
Source File: read.py From django-cachalot with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #6
Source File: read.py From django-cachalot with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #7
Source File: read.py From django-cachalot with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #8
Source File: views.py From connect with MIT License | 6 votes |
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 #9
Source File: views.py From connect with MIT License | 6 votes |
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 #10
Source File: base.py From wagtail with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #11
Source File: tests.py From django-protector with MIT License | 6 votes |
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 #12
Source File: models.py From django-protector with MIT License | 6 votes |
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 #13
Source File: test_management.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
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
Source File: config.py From django-river with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #15
Source File: test_management.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
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 #16
Source File: object_permission.py From kpi with GNU Affero General Public License v3.0 | 6 votes |
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 #17
Source File: object_permission.py From kpi with GNU Affero General Public License v3.0 | 6 votes |
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 #18
Source File: permissions.py From django-organice with Apache License 2.0 | 6 votes |
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 #19
Source File: views.py From connect with MIT License | 5 votes |
def get_queryset(self): """ Get the queryset of possible Users for the Permission Update View This view cannot be used to edit the permissions of the requesting user nor can it be used to edit the permissions of a superuser. """ return super(UpdateUserPermissionView, self).get_queryset().exclude( is_superuser=True).exclude(pk=self.request.user.pk)
Example #20
Source File: tests.py From allianceauth with GNU General Public License v2.0 | 5 votes |
def setUp(self): self.member = AuthUtils.create_member('auth_member') AuthUtils.add_main_character(self.member, 'test character', '1234', '2345', 'test corp', 'testc') self.member.email = 'auth_member@example.com' self.member.save() self.none_user = AuthUtils.create_user('none_user', disconnect_signals=True) self.none_user2 = AuthUtils.create_user('none_user2', disconnect_signals=True) self.none_user3 = AuthUtils.create_user('none_user3', disconnect_signals=True) self.no_perm_user = AuthUtils.create_user('no_perm_user', disconnect_signals=True) AuthUtils.disconnect_signals() self.no_perm_group = Group.objects.create(name="No Permission Group") self.test_group = Group.objects.create(name="Test group") self.test_group.user_set.add(self.none_user) self.test_group.user_set.add(self.none_user2) self.test_group.user_set.add(self.none_user3) self.permission = Permission.objects.get_by_natural_key(codename='audit_permissions', app_label='permissions_tool', model='permissionstool') self.test_group.permissions.add(self.permission) self.member.user_permissions.add(self.permission) AuthUtils.connect_signals()
Example #21
Source File: test_management.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def tearDown(self): Permission._meta.permissions = self._original_permissions Permission._meta.default_permissions = self._original_default_permissions ContentType.objects.clear_cache()
Example #22
Source File: signals.py From allianceauth with GNU General Public License v2.0 | 5 votes |
def m2m_changed_group_permissions(sender, instance, action, pk_set, *args, **kwargs): logger.debug("Received m2m_changed from group %s permissions with action %s" % (instance, action)) if instance.pk and (action == "post_remove" or action == "post_clear"): logger.debug("Checking if service permission changed for group {}".format(instance)) # As validating an entire groups service could lead to many thousands of permission checks # first we check that one of the permissions changed is, in fact, a service permission. perms = Permission.objects.filter(pk__in=pk_set) got_change = False service_perms = [svc.access_perm for svc in ServicesHook.get_services()] for perm in perms: natural_key = perm.natural_key() path_perm = "{}.{}".format(natural_key[1], natural_key[0]) if path_perm not in service_perms: # Not a service permission, keep searching continue for svc in ServicesHook.get_services(): if svc.access_perm == path_perm: logger.debug("Permissions changed for group {} on " "service {}, re-validating services for groups users".format(instance, svc)) def validate_all_groups_users_for_service(): logger.debug("Performing validation for service {}".format(svc)) for user in instance.user_set.all(): svc.validate_user(user) transaction.on_commit(validate_all_groups_users_for_service) got_change = True break # Found service, break out of services iteration and go back to permission iteration if not got_change: logger.debug("Permission change for group {} was not service permission, ignoring".format(instance))
Example #23
Source File: test_management.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def setUp(self): self._original_permissions = Permission._meta.permissions[:] self._original_default_permissions = Permission._meta.default_permissions self.app_config = apps.get_app_config('auth')
Example #24
Source File: signals.py From allianceauth with GNU General Public License v2.0 | 5 votes |
def m2m_changed_state_permissions(sender, instance, action, pk_set, *args, **kwargs): logger.debug("Received m2m_changed from state %s permissions with action %s" % (instance, action)) if instance.pk and (action == "post_remove" or action == "post_clear"): logger.debug("Checking if service permission changed for state {}".format(instance)) # As validating an entire groups service could lead to many thousands of permission checks # first we check that one of the permissions changed is, in fact, a service permission. perms = Permission.objects.filter(pk__in=pk_set) got_change = False service_perms = [svc.access_perm for svc in ServicesHook.get_services()] for perm in perms: natural_key = perm.natural_key() path_perm = "{}.{}".format(natural_key[1], natural_key[0]) if path_perm not in service_perms: # Not a service permission, keep searching continue for svc in ServicesHook.get_services(): if svc.access_perm == path_perm: logger.debug("Permissions changed for state {} on " "service {}, re-validating services for state users".format(instance, svc)) def validate_all_state_users_for_service(): logger.debug("Performing validation for service {}".format(svc)) for profile in instance.userprofile_set.all(): svc.validate_user(profile.user) transaction.on_commit(validate_all_state_users_for_service) got_change = True break # Found service, break out of services iteration and go back to permission iteration if not got_change: logger.debug("Permission change for state {} was not service permission, ignoring".format(instance))
Example #25
Source File: test_context_processors.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
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, "nonexistent")
Example #26
Source File: test_context_processors.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
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.force_login(u) response = self.client.get('/auth_processor_perms/') self.assertContains(response, "Has auth permissions") self.assertContains(response, "Has auth.add_permission permissions") self.assertNotContains(response, "nonexistent")
Example #27
Source File: __init__.py From Kiwi with GNU General Public License v2.0 | 5 votes |
def all_permissions_except(self, tested_permission): """ Make sure self.tester has all other permissions except the one required! """ for perm in Permission.objects.all(): user_should_have_perm(self.tester, perm) remove_perm_from_user(self.tester, tested_permission)
Example #28
Source File: __init__.py From Kiwi with GNU General Public License v2.0 | 5 votes |
def all_permissions_except(self, tested_permission): """ Make sure self.tester has all other permissions except the one required! """ for perm in Permission.objects.all(): user_should_have_perm(self.tester, perm) remove_perm_from_user(self.tester, tested_permission)
Example #29
Source File: test_me.py From donation-tracker with Apache License 2.0 | 5 votes |
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 #30
Source File: test_context_processors.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
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, "nonexistent")