def testHasModelPerms(self): from bop.api import has_model_perms, get_model_perms self.assertEqual(get_model_perms(Thing) ,get_model_perms(self.thing)) testa = User.objects.create_user('test-a', '*****@*****.**', 'test-a') self.assertFalse(has_model_perms(testa, Thing)) ct = ContentType.objects.get_for_model(Thing) permd = Permission.objects.get(codename='delete_thing', content_type=ct) testa.user_permissions.add(permd) # re-get the user to clear/re-fill the perms-cache testa = User.objects.get(username='******') self.assertTrue(has_model_perms(testa, Thing)) testa.delete()
def get_user_objects(self, user, permissions=None, check_model_perms=False): """ Will only return objects this user has permissions on Optionally filter for specific permissions This manager can be added to any Model and it will work like the default manager with this one extra method. class MyModel(models.Model): name = models.CharField(max_length=255) ... objects = UserObjectManager() If you are already using a custommanager you can use a different name or perhaps add UserObjectManager as an extra superclass to the existing custom manager. """ if user.is_superuser: return self.all() # importing here to avoid circular imports from bop.api import resolve, perm2dict, has_model_perms from bop.models import ObjectPermission # A quick check first if check_model_perms and not permissions: # If there are no specific permissions and check_model_perms # is set *and* the user has *any* (model) perms # UserObjectManager will return the entire set if has_model_perms(user, self.model): return self.all() if permissions: permissions = resolve(permissions, Permission, perm2dict) if check_model_perms: for p in permissions: if user.has_perm("%s.%s" % (self.model._meta.app_label, p.codename)): return self.all() ops = ObjectPermission.objects.get_for_model_and_user(self.model, user) if permissions: ops = ops.filter(permission__in=permissions) return self.filter(pk__in=ops.values_list("object_id", flat=True).distinct())