限制Django中对仅拥有内容的访问

5 投票
2 回答
2679 浏览
提问于 2025-04-17 19:30

我正在使用 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 的访问呢?

2 个回答

4

你可以通过自定义一个 授权 类来实现这个功能,比如可以写成下面这样:

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 
3

我最终的解决方案是参考了这个回答,作者是@JamesO。不过他给出的答案是针对django-tastypie的旧版本写的,因为在那之后,Authorization类进行了重写。以下是我的代码,供以后参考:

from tastypie.authorization import Authorization
from django.contrib.auth.models import Group
from extendedusers.models import ExtendedUser


class CustomAuthorization(Authorization):
    def read_list(self, object_list, bundle):
        clinician_group = Group.objects.get(name='clinician')
        if bundle.request and hasattr(bundle.request, 'user'):
            if clinician_group in bundle.request.user.groups.all():
                patients = ExtendedUser.objects.filter(clinician_id=bundle.request.user.id)
                object_list = object_list.filter(author__id__in=patients)
            else:
                object_list = object_list.filter(author=bundle.request.user)
            return object_list
        else:
            return object_list.none()

撰写回答