本文整理汇总了Python中guardian.shortcuts.get_perms方法的典型用法代码示例。如果您正苦于以下问题:Python shortcuts.get_perms方法的具体用法?Python shortcuts.get_perms怎么用?Python shortcuts.get_perms使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类guardian.shortcuts
的用法示例。
在下文中一共展示了shortcuts.get_perms方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: delete_all_permissions_group
# 需要导入模块: from guardian import shortcuts [as 别名]
# 或者: from guardian.shortcuts import get_perms [as 别名]
def delete_all_permissions_group(group_name, obj):
"""
Delete all permissions for a resource
Args:
group_name : Name of existing group
obj: Object that we are getting permission for
perm_list : List of permissions to be deleted
Returns:
"""
# Get the type of model
group = Group.objects.get(name=group_name)
perm_list = get_perms(group, obj)
for perm in perm_list:
remove_perm(perm, group, obj)
示例2: check_data_permissions
# 需要导入模块: from guardian import shortcuts [as 别名]
# 或者: from guardian.shortcuts import get_perms [as 别名]
def check_data_permissions(user, obj, method_type):
"""
Check user permissions for a data
Args:
user: User name
obj: resource
method_type: Mothod type specified in the post
Returns:
bool. True if the user has the permission on the resource
"""
if method_type == 'GET':
permission = 'read_volumetric_data'
elif method_type == 'POST':
permission = 'add_volumetric_data'
elif method_type == 'DELETE':
permission = 'delete_volumetric_data'
else:
raise BossError("Unable to get permissions for this request", ErrorCodes.INVALID_POST_ARGUMENT)
if permission in get_perms(user, obj):
return True
else:
return False
示例3: check_object_permissions
# 需要导入模块: from guardian import shortcuts [as 别名]
# 或者: from guardian.shortcuts import get_perms [as 别名]
def check_object_permissions(user, obj, method_type):
"""
Check permissions for object services (currently only the reserve service uses this)
Args:
user: User name
obj: resource
method_type: Mothod type specified in the post
Returns:
bool. True if the user has the permission on the resource
"""
if method_type == 'GET':
permission = 'add_volumetric_data'
else:
raise BossError("Invalid method type. This query only supports a GET", ErrorCodes.INVALID_POST_ARGUMENT)
if permission in get_perms(user, obj):
return True
else:
return False
示例4: apply_permissions
# 需要导入模块: from guardian import shortcuts [as 别名]
# 或者: from guardian.shortcuts import get_perms [as 别名]
def apply_permissions(self, data, revert=False):
with transaction.atomic():
for identity in data["selectedIdentities"]:
if identity["type"] == "group":
identityModel = Group.objects.get(pk=identity["id"])
else:
identityModel = User.objects.get(pk=identity["id"])
for card in data["selectedCards"]:
# TODO The following try block is here because the key for the nodegroupid in the new permission manager
# is 'nodegroupid' where it was 'nodegroup' in the old permission manager. Once the old permission manager is deleted
# we can replace it with `nodegroupid = card['nodegroupid']`
try:
nodegroupid = card["nodegroupid"]
except KeyError:
nodegroupid = card["nodegroup"]
nodegroup = models.NodeGroup.objects.get(pk=nodegroupid)
# first remove all the current permissions
for perm in get_perms(identityModel, nodegroup):
remove_perm(perm, identityModel, nodegroup)
if not revert:
# then add the new permissions
for perm in data["selectedPermissions"]:
assign_perm(perm["codename"], identityModel, nodegroup)
示例5: test_resource_instance_permission_assignment
# 需要导入模块: from guardian import shortcuts [as 别名]
# 或者: from guardian.shortcuts import get_perms [as 别名]
def test_resource_instance_permission_assignment(self):
"""
Test that we can assign resource instance permissions
"""
self.client.login(username="ben", password="Test12345!")
payload = {
"selectedIdentities": [
{
"type": "group",
"id": 2,
"selectedPermissions": [{"codename": "change_resourceinstance"}, {"codename": "delete_resourceinstance"}],
}
],
"selectedInstances": [{"resourceinstanceid": self.resource_instance_id}],
}
url = reverse("resource_permission_data")
post_data = JSONSerializer().serialize(payload)
content_type = "application/x-www-form-urlencoded"
self.client.post(url, post_data, content_type)
group = Group.objects.get(pk=payload["selectedIdentities"][0]["id"])
resource = ResourceInstance.objects.get(resourceinstanceid=self.resource_instance_id)
assigned_perms = get_perms(group, resource)
self.assertTrue("change_resourceinstance" in assigned_perms and "delete_resourceinstance" in assigned_perms)
示例6: test_resource_instance_permission_deletion
# 需要导入模块: from guardian import shortcuts [as 别名]
# 或者: from guardian.shortcuts import get_perms [as 别名]
def test_resource_instance_permission_deletion(self):
"""
Test that we can delete resource instance permissions
"""
self.client.login(username="ben", password="Test12345!")
payload = {
"selectedIdentities": [
{
"type": "group",
"id": 2,
"selectedPermissions": [{"codename": "change_resourceinstance"}, {"codename": "delete_resourceinstance"}],
}
],
"selectedInstances": [{"resourceinstanceid": self.resource_instance_id}],
}
url = reverse("resource_permission_data")
post_data = JSONSerializer().serialize(payload)
content_type = "application/x-www-form-urlencoded"
group = Group.objects.get(pk=payload["selectedIdentities"][0]["id"])
resource = ResourceInstance.objects.get(resourceinstanceid=self.resource_instance_id)
assign_perm("delete_resourceinstance", group, resource)
self.client.delete(url, post_data, content_type)
assigned_perms = get_perms(group, resource)
self.assertTrue("change_resourceinstance" not in assigned_perms and "delete_resourceinstance" not in assigned_perms)
示例7: test_creator_has_permissions
# 需要导入模块: from guardian import shortcuts [as 别名]
# 或者: from guardian.shortcuts import get_perms [as 别名]
def test_creator_has_permissions(self):
"""
Test user that created instance has full permissions
"""
user = User.objects.create_user(username="sam", email="sam@samsclub.com", password="Test12345!")
user.save()
group = Group.objects.get(name="Resource Editor")
group.user_set.add(user)
test_resource = Resource(graph_id=self.search_model_graphid)
test_resource.save(user=user)
perms = set(get_perms(user, test_resource))
self.assertEqual(perms, {"view_resourceinstance", "change_resourceinstance", "delete_resourceinstance"})
示例8: test_process_register_all
# 需要导入模块: from guardian import shortcuts [as 别名]
# 或者: from guardian.shortcuts import get_perms [as 别名]
def test_process_register_all(self):
out, err = StringIO(), StringIO()
call_command("register", stdout=out, stderr=err)
self.assertTrue("Inserted test-min" in out.getvalue())
self.assertTrue(
"Skip processor test-min: newer version installed" in err.getvalue()
)
# Check that contributor gets all permissions.
process = Process.objects.first()
self.assertEqual(len(get_perms(self.admin, process)), 3)
out, err = StringIO(), StringIO()
call_command("register", stdout=out, stderr=err)
self.assertTrue(
"Skip processor test-min: same version installed" in out.getvalue()
)
self.assertTrue(
"Skip processor test-bloated: same version installed" in out.getvalue()
)
self.assertTrue(
"Skip processor test-min: newer version installed" in err.getvalue()
)
out, err = StringIO(), StringIO()
call_command("register", force=True, stdout=out, stderr=err)
self.assertTrue("Updated test-min" in out.getvalue())
self.assertTrue("Updated test-bloated" in out.getvalue())
self.assertTrue(
"Skip processor test-min: newer version installed" in err.getvalue()
)
示例9: get_permissions_group
# 需要导入模块: from guardian import shortcuts [as 别名]
# 或者: from guardian.shortcuts import get_perms [as 别名]
def get_permissions_group(group_name, obj):
"""
Return the permissions for a group
Args:
group_name : Name of existing group
obj: Object that we are getting permission for
Returns:
List of permissions
"""
# Get the type of model
group = Group.objects.get(name=group_name)
return get_perms(group,obj)
示例10: check_resource_permissions
# 需要导入模块: from guardian import shortcuts [as 别名]
# 或者: from guardian.shortcuts import get_perms [as 别名]
def check_resource_permissions(user, obj, method_type):
"""
Check user permissions for a resource object
Args:
user: User name
obj: Obj
method_type: Method type specified in the request
Returns:
bool. True if the user has the permission on the resource
"""
if method_type == 'GET':
permission = 'read'
elif method_type == 'POST':
permission = 'add'
elif method_type == 'PUT':
permission = 'update'
elif method_type == 'DELETE':
permission = 'delete'
else:
raise BossError("Unable to get permissions for this request", ErrorCodes.INVALID_POST_ARGUMENT)
if permission in get_perms(user, obj):
return True
else:
return False
示例11: test_activation_valid
# 需要导入模块: from guardian import shortcuts [as 别名]
# 或者: from guardian.shortcuts import get_perms [as 别名]
def test_activation_valid(self):
"""
Valid activation of an user.
Activation of an user with a valid ``activation_key`` should activate
the user and set a new invalid ``activation_key`` that is defined in
the setting ``USERENA_ACTIVATED``.
"""
user = UserenaSignup.objects.create_user(**self.user_info)
active_user = UserenaSignup.objects.activate_user(
user.userena_signup.activation_key
)
profile = get_user_profile(user=active_user)
# The returned user should be the same as the one just created.
self.assertEqual(user, active_user)
# The user should now be active.
self.assertTrue(active_user.is_active)
# The user should have permission to view and change its profile
self.assertTrue("view_profile" in get_perms(active_user, profile))
self.assertTrue("change_profile" in get_perms(active_user, profile))
# The activation key should be the same as in the settings
self.assertEqual(
active_user.userena_signup.activation_key,
userena_settings.USERENA_ACTIVATED,
)
示例12: test_share_content
# 需要导入模块: from guardian import shortcuts [as 别名]
# 或者: from guardian.shortcuts import get_perms [as 别名]
def test_share_content(self):
data_1 = Data.objects.create(
contributor=self.owner, process=self.process, name="Data 1"
)
data_2 = Data.objects.create(
contributor=self.owner, process=self.process, name="Data 2"
)
entity_1 = Entity.objects.create(contributor=self.owner, name="Entity 1")
entity_2 = Entity.objects.create(contributor=self.owner, name="Entity 2")
self.collection.data.add(data_1, data_2)
self.collection.entity_set.add(entity_1, entity_2)
assign_perm("view_collection", self.user1, self.collection)
assign_perm("share_collection", self.user1, self.collection)
assign_perm("view_data", self.user1, data_1)
assign_perm("view_data", self.user1, data_2)
assign_perm("share_data", self.user1, data_1)
assign_perm("view_entity", self.user1, entity_1)
assign_perm("view_entity", self.user1, entity_2)
assign_perm("share_entity", self.user1, entity_1)
data = {"users": {"add": {self.user2.pk: ["view"]}}}
resp = self._detail_permissions(self.collection.pk, data, self.user1)
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(
UserObjectPermission.objects.filter(user=self.user2).count(), 1
)
data = {"users": {"add": {self.user2.pk: ["view"]}}, "share_content": "true"}
resp = self._detail_permissions(self.collection.pk, data, self.user1)
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(
UserObjectPermission.objects.filter(user=self.user2).count(), 3
)
self.assertEqual(len(get_perms(self.user2, data_1)), 1)
self.assertEqual(len(get_perms(self.user2, data_2)), 0)
self.assertEqual(len(get_perms(self.user2, entity_1)), 1)
self.assertEqual(len(get_perms(self.user2, entity_2)), 0)
data = {"users": {"remove": {self.user2.pk: ["view"]}}}
resp = self._detail_permissions(self.collection.pk, data, self.user1)
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(
UserObjectPermission.objects.filter(user=self.user2).count(), 2
)
data = {"users": {"remove": {self.user2.pk: ["view"]}}, "share_content": "true"}
resp = self._detail_permissions(self.collection.pk, data, self.user1)
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(
UserObjectPermission.objects.filter(user=self.user2).count(), 0
)
示例13: test_data_duplicate_duplicate
# 需要导入模块: from guardian import shortcuts [as 别名]
# 或者: from guardian.shortcuts import get_perms [as 别名]
def test_data_duplicate_duplicate(self):
process1 = Process.objects.create(
contributor=self.user, type="data:test:first:",
)
process2 = Process.objects.create(
contributor=self.user,
input_schema=[{"name": "data_field", "type": "data:test:first:"},],
output_schema=[{"name": "json_field", "type": "basic:json:"},],
)
input_data = Data.objects.create(contributor=self.user, process=process1)
data = Data.objects.create(
contributor=self.user, process=process2, input={"data_field": input_data.id}
)
data_location = create_data_location()
data_location.data.add(data)
data.output = {"json_field": {"foo": "bar"}}
data.status = Data.STATUS_DONE
data.save()
data.migration_history.create(migration="migration_1")
# Duplicate.
duplicate = data.duplicate(self.contributor)
duplicate_of_duplicate = duplicate.duplicate()
self.assertEqual(
duplicate.contributor.id, duplicate_of_duplicate.contributor.id
)
# Assert location
self.assertEqual(duplicate.location.id, duplicate_of_duplicate.location.id)
# Assert dependencies.
self.assertEqual(DataDependency.objects.count(), 3)
self.assertTrue(
DataDependency.objects.filter(
kind=DataDependency.KIND_IO,
parent=input_data,
child=duplicate_of_duplicate,
).exists()
)
# Assert storage
self.assertEqual(
duplicate_of_duplicate.storages.first().id, Storage.objects.first().id
)
# Assert migration history
self.assertEqual(DataMigrationHistory.objects.count(), 3)
self.assertEqual(
duplicate_of_duplicate.migration_history.latest("created").migration,
"migration_1",
)
# Assert permissions.
self.assertEqual(len(get_perms(self.contributor, duplicate_of_duplicate)), 4)
示例14: check_permissions
# 需要导入模块: from guardian import shortcuts [as 别名]
# 或者: from guardian.shortcuts import get_perms [as 别名]
def check_permissions(self):
"""
Checks that all permissions are set correctly for the users.
:return: A set of users whose permissions was wrong.
"""
# Variable to supply some feedback
changed_permissions = []
changed_users = []
warnings = []
# Check that all the permissions are available.
for model, perms in ASSIGNED_PERMISSIONS.items():
if model == "profile":
model_obj = get_profile_model()
else:
model_obj = get_user_model()
model_content_type = ContentType.objects.get_for_model(model_obj)
for perm in perms:
try:
Permission.objects.get(
codename=perm[0], content_type=model_content_type
)
except Permission.DoesNotExist:
changed_permissions.append(perm[1])
Permission.objects.create(
name=perm[1], codename=perm[0], content_type=model_content_type
)
# it is safe to rely on settings.ANONYMOUS_USER_NAME since it is a
# requirement of django-guardian
for user in get_user_model().objects.exclude(
username=settings.ANONYMOUS_USER_NAME
):
try:
user_profile = get_user_profile(user=user)
except ObjectDoesNotExist:
warnings.append(
_("No profile found for %(username)s") % {"username": user.username}
)
else:
all_permissions = get_perms(user, user_profile) + get_perms(user, user)
for model, perms in ASSIGNED_PERMISSIONS.items():
if model == "profile":
perm_object = get_user_profile(user=user)
else:
perm_object = user
for perm in perms:
if perm[0] not in all_permissions:
assign_perm(perm[0], user, perm_object)
changed_users.append(user)
return (changed_permissions, changed_users, warnings)
示例15: can_view_profile
# 需要导入模块: from guardian import shortcuts [as 别名]
# 或者: from guardian.shortcuts import get_perms [as 别名]
def can_view_profile(self, user):
"""
Can the :class:`User` view this profile?
Returns a boolean if a user has the rights to view the profile of this
user.
Users are divided into four groups:
``Open``
Everyone can view your profile
``Closed``
Nobody can view your profile.
``Registered``
Users that are registered on the website and signed
in only.
``Admin``
Special cases like superadmin and the owner of the profile.
Through the ``privacy`` field a owner of an profile can define what
they want to show to whom.
:param user:
A Django :class:`User` instance.
"""
# Simple cases first, we don't want to waste CPU and DB hits.
# Everyone.
if self.privacy == "open":
return True
# Registered users.
elif self.privacy == "registered" and isinstance(user, get_user_model()):
return True
# Checks done by guardian for owner and admins.
elif "view_profile" in get_perms(user, self):
return True
# Fallback to closed profile.
return False