2017-06-10 49 views
0

我想要授予某些用戶檢索訪問權限,某些用戶更新訪問權限,並且不會將未經身份驗證的用戶檢索/更新訪問權限授予我的DRF API。
在我的擴展用戶模型中,我有兩個字段定義是否允許用戶檢索或更新API。我應該如何在我的DRF自定義權限類中編寫邏輯以檢查這兩個字段並根據True或False來授予檢索或更新?我應該爲此使用ViewSet還是使用帶有Mixins的單獨ListAPIView,RetrieveAPIView和UpdateAPIView類?做這個的最好方式是什麼?Django - 如何將自定義權限授予DRF中的某些用戶?

models.py

class UserProfile(models.Model): 
    user = models.OneToOneField(User) 
    allowRetrieveAPI = models.BooleanField(default=False,) 
    allowUpdateAPI = models.BooleanField(default=False,) 

class Track(models.Model):  
    user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL, verbose_name="Submitted by", default=1) 
    artist = models.CharField(max_length=100,) 
    title = models.CharField(max_length=100,) 

views.py

class CheckAPIPermissions(permissions.BasePermission): 
    # allow retrieve if userprofile.allowReadAPI is True 
    # allow update if user userprofile.allowUpdateAPI is True 

    def has_permission(self, request, view): 
     # return something 
    def check_object_permission(self, user, obj): 
     # return something  
    def has_object_permission(self, request, view, obj): 
     # return something 

class TrackViewSet(viewsets.ModelViewSet): 
    queryset = Track.objects.all() 
    serializer_class = TrackSerializer 
    permission_classes = (CheckAPIPermissions,) 
+0

每個人都可以訪問列表方法,然後呢? – zaidfazil

+0

我忘記了,但如果他們能夠檢索,他們應該被允許列表方法。 – bayman

回答

1
class CheckAPIPermissions(permissions.BasePermission): 
    # allow retrieve if userprofile.allowReadAPI is True 
    # allow update if user userprofile.allowUpdateAPI is True 

    def has_permission(self, request, view): 
     if request.user.is_superuser: 
      return True 
     elif request.user and request.user.is_authenticated(): 
      if (request.user.userprofile.allowRetrieveAPI or request.user.userprofile.allowUpdateAPI) and view.action == 'retrieve': 
       return True 
      elif request.user.userprofile.allowUpdateAPI and view.action == 'update': 
       return True 
     return False 

    def check_object_permission(self, user, obj): 
     return (user and user.is_authenticated() and (user.is_staff or obj == user)) 


    def has_object_permission(self, request, view, obj): 
     if request.user.is_superuser: 
      return True 
     elif request.user and request.user.is_authenticated(): 
      if (request.user.userprofile.allowRetrieveAPI or request.user.userprofile.allowUpdateAPI) and view.action == 'retrieve': 
       return request.user == obj 
      elif request.user.userprofile.allowUpdateAPI and view.action == 'update': 
       return request.user == obj 
     return False 

我沒有測試過,只是在時間的尼克寫道。