django 如何根据用户组允许/拒绝API权限

vyswwuz2  于 2023-01-31  发布在  Go
关注(0)|答案(1)|浏览(166)

我有2组用户:Creator和查看器.创建器can create, update, view and delete data, while查看器'只能查看数据。
我不明白如何实现他们容易。后来,我可能不得不允许某些污垢不同的模型。我觉得如果小组可以有自定义的访问,我将有完全的控制,也许一个自定义类?
我已经分离了API,现在需要检查组是否匹配,然后允许对API执行操作。
serializer.py

from rest_framework import serializers
from trackit_create.models import upload_status_image, track_info
from django.contrib.auth.models import Group

   

class StatusSerializer(serializers.ModelSerializer):
    
    class Meta:
        model=track_info
        fields = ('id','description','Manufacture','user','Cost','image')

views.py

# has option to create data 
class AssetCreator(mixins.CreateModelMixin, generics.ListAPIView,mixins.ListModelMixin):
    serializer_class =StatusSerializer
    authentication_classes= [TokenAuthentication]
    permission_classes = [permissions.IsAuthenticated]

    # def get(self, request, *args, **kwags):
    #     return self.get(request, *args, **kwags)

    def get_queryset(self):
        qs= track_info.objects.all()
        query= self.request.GET.get('q')
        if query is not None:
            qs=qs.filter(content__icontains=query)
            return qs
    
    def get_object(self):
        request = self.request
        passed_id = request.GET.get('id',None)
        queryset =self.get_queryset()

        if passed_id is not None:
            obj = get_object_or_404(queryset, id = passed_id)
            self.check_object_permissions(request, obj)        
        return obj       
        
    def post(self, request, *args, **kwags):
        return self.create(request, *args, **kwags)

# has permision to edit, delete data based on the 
class StatusAPIDetailView(mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.RetrieveAPIView):
    
      
    serializer_class = StatusSerializer
    authentication_classes= [TokenAuthentication]    
    permission_classes = [permissions.IsAuthenticated]    
    queryset= track_info.objects.all()
    lookup_field ='id'

  
    def put(self,request,*args,**kwargs):
        return self.update(request, *args, **kwargs)
    
    
    def delete(self,request,*args,**kwargs):
        return self.destroy (request, *args, **kwargs)
    
    def patch(self,request,*args,**kwargs):
        return self.update (request, *args, **kwargs)
    
    def perform_update(self, serializer):
        serializer.save(updated_by_user= self.request.user)
        
    def perform_destroy(self,request):
        if instance is not None:
            return instance.delete()        
        return None
    

class AssetGetlist(APIView):
    permission_classes = [permissions.IsAuthenticated]
    authentication_classes= [TokenAuthentication]
    def get(self,request,format=None):
        qs = track_info.objects.all()
        query_set = Group.objects.filter(user = request.user)
        print ("fgfgf",query_set) # getting the group user is in 
        pm=print(query_set[0])
        #data={'grp':pm}           
        serializer= StatusSerializer(qs, many=True)
        return Response(serializer.data, status =status.HTTP_200_OK)

models.py

class track_info(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= models.CASCADE)
    Entry_date = models.DateField(auto_now_add=True) 
    description = models.TextField(null=True, blank=True)
    image = models.ImageField(null=True, blank=True)
    Manufacture= models.CharField(max_length=100)
    Cost = models.IntegerField(null=True, blank=True)

我引用了https://www.botreetechnologies.com/blog/django-user-groups-and-permission,但无法将其与我的代码关联起来。

wgx48brx

wgx48brx1#

您可以通过扩展Django Rest Framework BasePermission来创建自定义权限类。
您需要实现has_permission方法,在该方法中您可以访问request和view对象。您可以检查request.user是否在正确的组中,并根据需要返回True/False。
大概是这样的

from rest_framework.permissions import BasePermission

class CreatorOnly(BasePermission):
    def has_permission(self, request, view):
        if request.user.groups.filter(name='your_creator_group').exists() and request.method in YOUR_ALLOWED_METHODS:
           return True
        return False

然后将此添加到您的查看权限列表中:

class AssetCreator(mixins.CreateModelMixin, generics.ListAPIView,mixins.ListModelMixin):
    ...
    permission_classes = [CreatorOnly]

相关问题