2016-07-13 1 views
3

새로운 사용자 유형 필드를 추가하기 위해 Django 기본 'User'모델을 확장했습니다. 사용자 유형 범주는 사용자, 관리자뷰어입니다. 그리고 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 [] 
관련 문제