2016-07-13 14 views
3

我已經擴展了Django默認的「用戶」模型以添加新的用戶類型字段。用戶類型類別爲用戶,管理員查看器。 我想爲此使用tastypie實現RESTapi,並根據用戶類型授予訪問該api的權限。例如 管理員用戶可以完全訪問此API,用戶可以查看所有字段,但只能更新自己的帳戶,查看者無​​法訪問此API。如何在tastypie中使用自定義用戶類型來限制GET,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 [] 
相關問題