如何在 tastypie 中使用自定义用户类型限制 GET,POST 对资源的访问

how to limit GET,POST access to resources using customize user type in tastypie

我扩展了 Django 默认 'User' 模型以添加新的用户类型字段。用户类型类别为 useradminviewer。 我想为此使用 tastypie 实现 RESTapi,并根据用户类型授予访问该 api 的权限。 例如,管理员用户对此 API 具有完全访问权限,用户可以查看所有字段但只能更新自己的帐户,查看者无​​权访问此 api.

api.py

    class UserResource(ModelResource):
        class Meta:
            queryset = CustomUser.objects.all()
            resource_name = 'user'
            allowed_methods = ['get','post']
            filtering = {"id": ALL}
            excludes = ['is_staff','password','is_superuser','id','is_active','date_joined']
            authentication =  BasicAuthentication()

处理此问题的最佳方法是什么?

首先,编写您自己的身份验证class。在此 class 检查用户是否为 查看者 。如果是,return 错误。

class MyAuthentication(BasicAuthentication):
    def is_authenticated(self, request, **kwargs):
        is_authenticated = super(MyAuthentication, self).is_authenticated(request, **kwargs)
        if not is_authenticated:
            return False
        return request.user.user_type_category != 'viewer'

其次,写下你自己的授权class。在这个 class 覆盖函数 [create|update|delete]_[list|detail] 中,在 create/delete 函数中检查用户是否是 user。如果是,则引发异常(详细)或 return [](在列表中)。在更新中检查用户是否更新自己。如果否,则引发异常或 return [].

class MyAuthorization(DjangoAuthorization):
    def create_detail(self, object_list, bundle):
        super(MyAuthorization, self).create_detail(object_list, bundle)
        if bundle.request.user.user_type_category != 'admin':
            raise Unauthorized("You are not allowed to create that resource.")
        return True

    def create_list(self, object_list, bundle):
        if bundle.request.user.user_type_category != 'admin':
            return []
        return super(MyAuthorization, self).create_list(object_list, bundle)

    def delete_detail(self, object_list, bundle):
        super(MyAuthorization, self).delete_detail(object_list, bundle)
        if bundle.request.user.user_type_category != 'admin':
            raise Unauthorized("You are not allowed to delete that resource.")
        return True

    def delete_list(self, object_list, bundle):
        if bundle.request.user.user_type_category != 'admin':
            return []
        return super(MyAuthorization, self).delete_list(object_list, bundle)

    def update_detail(self, object_list, bundle):
        super(MyAuthorization, self).delete_detail(object_list, bundle)
        if bundle.request.user != bundle.obj:
            raise Unauthorized("You are not allowed to update that resource.")
        return True

    def update_list(self, object_list, bundle):
        object_list = super(MyAuthorization, self).update_list(object_list, bundle)
        if object_list.count() == object_list.filter(pk=bundle.obj.pk).count():
            return object_list
        return []