python – 限制只访问自有内容django
作者:互联网
我正在使用django-tastypie编写API.我有两个自定义权限问题,我希望django-guardian可以修复.
我有两个用户组临床医生和患者.临床医生应该能够访问仅属于他们的患者的对象,患者应该只能访问他们自己创建的对象.
我的代码如下:
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'auth/user'
excludes = ['email', 'password', 'is_superuser']
class BlogPostResource(ModelResource):
author = fields.ToOneField(UserResource, 'author', full=True)
class Meta:
queryset = BlogPost.objects.all()
resource_name = 'posts'
allowed_methods = ["get", "post"]
# Add it here.
authentication = BasicAuthentication()
authorization = DjangoAuthorization()
filtering = {
'author': ALL_WITH_RELATIONS,
}
如何使用权限限制对此BlogPostResource的访问?
解决方法:
您可以使用自定义Authorization类来实现此目的,例如:
class CustomAuthorization(Authorization):
def apply_limits(self, request, object_list):
...
clin_group = Group.objects.get(name='YOUR GROUP')
if request and hasattr(request, 'user'):
if clin_group in request.user.groups.all():
object_list = object_list.filter(user__in=request.user.patients.all()) # or however you stop clinician>patient relation
else:
object_list = object_list.filter(user=request.user)
return object_list
标签:python,django,tastypie,django-guardian 来源: https://codeday.me/bug/20190529/1179129.html