2016-07-13 10 views
3

新しいユーザタイプフィールドを追加するための拡張Djangoデフォルト 'User'モデルがあります。ユーザータイプカテゴリは、ユーザー,adminおよびビューアです。 そして私はこれを使ってTastypieを使ってRESTapiを実装し、ユーザータイプに基づいてそのAPIにアクセスする権限を与えたいと思っています。 たとえば、管理者ユーザーはこのAPIへのフルアクセス権を持ちます。ユーザーはすべてのフィールドを表示できますが、自分のアカウントのみを更新できます。ビューアはこのAPIにアクセスできません。GETを制限する方法、Tastypieでカスタマイズしたユーザタイプを使用してリソースにPOSTアクセスする

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() 

これを処理するための最良の方法は何ですか?

答えて

0

まず、独自の認証クラスを作成します。このクラスでは、ユーザがビューアかどうかをチェックします。はいの場合はFalseを返します。

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' 

次に、独自の認証クラスを作成します。このクラスでは、関数[create|update|delete]_[list|detail]を上書きし、作成/削除機能で、ユーザがユーザであるかどうかをチェックします。 「はい」の場合は、例外(詳細)を発生させるか、[](リスト)を返します。更新時にユーザーが自分自身を更新するかどうかを確認します。いいえの場合は、例外を発生させるか、[]を返します。

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 [] 
関連する問題