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か? これらは実装の詳細であるように思われ、単純にorを返すことができるはずです。ImmediateHttpResponseHttpUnauthorizedTrueFalse

4

3 に答える 3

1

tastypie 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

長期的には、次のような認可クラスを使用して django-guardian をアプリケーションに統合する方がはるかに優れています。

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

于 2013-04-28T09:57:45.027 に答える
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 に答える