Django - 如何向DRF中的某些用户授予自定义权限?

时间:2017-06-10 18:28:08

标签: django django-rest-framework

我想授予某些用户检索访问权限,某些用户更新访问权限,并且未经身份验证的用户无法检索/更新访问我的DRF API。
在我的扩展用户模型中,我有两个字段,用于定义是否允许用户检索或更新API。我应该如何编写DRF自定义权限类中的逻辑来检查这两个字段,并根据True还是False授予检索或更新权限?我应该使用ViewSet还是使用单独的ListAPIView,RetrieveAPIView和UpdateAPIView类与Mixins?这样做的最佳方式是什么?

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

1 个答案:

答案 0 :(得分: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

我还没有测试过,只是在一段时间内写道。