python - 限制对仅拥有的内容 django 的访问

标签 python django tastypie django-guardian

我正在使用 django-tastypie 编写 API .我希望有两个自定义权限问题 django-guardian可以修复。

我有两个用户组 Clinicians 和 Patients。临床医生应该能够访问只属于他们的患者的对象,而患者应该只能访问他们自己创建的对象。

我的代码如下:

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 的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15477521/

相关文章:

python - 使用 API key 对开发人员进行身份验证,并使用基本身份验证/OAuth 对用户进行身份验证

python - 类型对象 'ModelDeclarativeMetaclass' 没有属性 'Meta'

python - 使用 python 设置 dockerized Couchdb

python - 平面文件NoSQL解决方案

python - 无法从 JSON 对象在 Python 中打印字符 '\u2019'

python - 使用 websockets 和 python/django(/扭曲?)

django - Django 管理界面中的只读模型?

python - 使用 pip 安装后找不到 cookiecutter 命令

django - 当我使用中间模型时,多对多关系并不是唯一的。

php - Flask - 在提交表单后保持复选框被选中