Example #1
0
    def test_permissions_instances(self):
        """
        test util.Permissions.instances
        """

        perms_a = Permissions(self.users["user_a"])
        perms_b = Permissions(self.users["user_b"])
        perms_admin = Permissions(self.users["user_admin_a"])

        for i in range(1, 4):
            ModelA.objects.create(name=f"Test {i}")

        # user a should have read to all 3 instances of model a
        # through implicit permissions
        instances = perms_a.instances(ModelA, "r")
        self.assertEqual(len(instances), 3)

        # user as should have read to to 0 instances of model a
        # through explicit permissions
        instances = perms_a.instances(ModelA, "r", explicit=True)
        self.assertEqual(len(instances), 0)

        # add user a permission to first isntance of model a
        # and reload permissions util
        self.users["user_a"].grainy_permissions.add_permission(
            ModelA.objects.first(), "r")
        perms_a.load(refresh=True)

        # user a should now habe read to 1 instances of model a
        # through explicit permissions
        instances = perms_a.instances(ModelA, "r", explicit=True)
        self.assertEqual(len(instances), 1)

        # user b should not have any
        instances = perms_b.instances(ModelA, "r")
        self.assertEqual(len(instances), 0)

        # deny user a permissions to first instance of model a
        # and reload permissions util
        self.users["user_a"].grainy_permissions.add_permission(
            ModelA.objects.first(), 0)
        perms_a.load(refresh=True)

        # user a should now have read access to 2 instances of model a
        instances = perms_a.instances(ModelA, "r")
        self.assertEqual(len(instances), 2)

        # admin user should have read to all 3 instances of model a
        # through grant all
        instances = perms_admin.instances(ModelA, "r")
        self.assertEqual(len(instances), 3)

        # admin user should have read to 0 instances of model
        # when ignoring grant all
        instances = perms_admin.instances(ModelA, "r", ignore_grant_all=True)
        self.assertEqual(len(instances), 0)
Example #2
0
from django_grainy.util import Permissions

# give user full permissions to model (any instance)
user.grainy_permissions.add(TestModelA, "crud")

# give user full permissions to a specific instance
instance = TestModelA.objects.get(id=1)
user.grainy_permissions.add(instance, "crud")

# check user permission on model class
perms = Permissions(user)
perms.check(TestModelA, "r")  # True

# check user permission on instance
perms.check(instance, "r")  # True

# check permissions to the name field
perms.check((instance, "name"), "r")

# return all instances of the model according to permissions
instances = perms.instances(TestModelA, "r")

# this could also take a queryset
instances = perms.instances(TestModelA.objects.filter(id__gt=10), "r")