如何在tastypie中使用DjangoAuthorization()来限制对资源的GET访问

And*_*arr 2 python django tastypie

我正在使用tastypie来创建RESTful API.我根据django管理员权限限制了用户授权. 根据文档,我正在尝试实现DjangoAuthorization().

class myResource(ModelResource):
   class Meta:
      queryset = myModel.objects().all()
      allowed_methods = ['get','post']
      authentication = ApiKeyAuthentication()
      authorization = DjangoAuthorization()
Run Code Online (Sandbox Code Playgroud)

目前,fakeuser完全没有Django权限的用户myModel仍然可以从api获取数据.该用户被适当地限制POST数据.

tl; dr如何扩展DjangoAuthorization()类以限制模型上没有Django权限的用户的GET

Aam*_*nan 6

编写您自己的授权后端,DjangoAuthorization根据您的标准覆盖访问方法,read_detail如下所示覆盖(GET)方法的一个示例:

from tastypie.authorization import DjangoAuthorization
from tastypie.exceptions import Unauthorized

class CustomDjangoAuthorization(DjangoAuthorization):

    def read_detail(self, object_list, bundle):
        result = super(CustomDjangoAuthorization, self).read_detail(object_list, bundle)

        # now we check here for specific permission
        if not bundle.request.user.has_perm('any_permission'):
            raise Unauthorized("You are not allowed to access that resource.")

        return result
Run Code Online (Sandbox Code Playgroud)

现在CustomDjangoAuthorization在资源中使用class:

class myResource(ModelResource):
   class Meta:
      queryset = myModel.objects().all()
      allowed_methods = ['get','post']
      authentication = ApiKeyAuthentication()
      authorization = CustomDjangoAuthorization()
Run Code Online (Sandbox Code Playgroud)