0

我已将行级授权添加到 Tastypie 资源,如下所示:

from tastypie.exceptions import ImmediateHttpResponse
from tastypie.http import HttpUnauthorized

class MyResource(ModelResources):
    ...
    def is_authorized(self, request, object=None):
        super(MyResource, self).is_authorized(request, object)
        if object and (object.user != request.user):
            raise ImmediateHttpResponse(response=HttpUnauthorized())

为简洁起见,我省略了通常的导入,只指定了与问题相关的导入。

我的问题是,有没有一种更清洁的方法来覆盖is_authorized而不必导入ImmediateHttpResponseand HttpUnauthorized?在我看来,这些是实现细节,我应该能够简单地返回Trueor False

4

3 回答 3

1

美味派 0.9.12 的文档就是一个很好的例子。

https://django-tastypie.readthedocs.org/en/v0.9.12/authorization.html#implementing-your-own-authorization

这是“阅读”部分——其余部分请参见文档:

class UserObjectsOnlyAuthorization(Authorization):

    def read_list(self, object_list, bundle):
        # This assumes a ``QuerySet`` from ``ModelResource``.
        return object_list.filter(user=bundle.request.user)

    def read_detail(self, object_list, bundle):
        # Is the requested object owned by the user?
        return bundle.obj.user == bundle.request.user

    # DON'T FORGET TO IMPLEMENT METHODS FOR CREATE/UPDATE/DELETE as shown in the docs.

您会注意到UserObjectsOnlyAuthorization.read_detail()返回 True/False。该read_list方法将返回一个空列表,根据文档这是可以接受的,但Unauthorized如果您愿意,也可以引发异常。

于 2013-03-21T01:53:59.387 回答
0

虽然您的代码非常好,但如果您不想导入响应类,那么更简洁的方法是编写授权类并在您的 Resource 类中使用它

from tastypie.authorization import Authorization
class RowLevelAuthorization(Authorization):
    def is_authorized(self, request, object=None):
        if object and (object.user != request.user):
            return False
        else:
            return True

class MyResource(ModelResources):
    class Meta:
        authorization = RowLevelAuthorization()
于 2013-03-13T14:57:05.503 回答
0

从长远来看,最好将 django-guardian 集成到您的应用程序中,并使用如下授权类:

https://gist.github.com/airtonix/5476453

于 2013-04-28T09:57:45.027 回答