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

时间:2014-06-12 16:30:17

标签: python django tastypie

我正在使用tastypie来创建RESTful API。我根据django管理员权限限制了用户授权。 Per the docs,我正在努力实施DjangoAuthorization()

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

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

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

1 个答案:

答案 0 :(得分: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

现在在资源中使用CustomDjangoAuthorization类:

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