DRF的权限认证

1、自定义权限数据库

utils文件夹下新建permissions.py,代码以下:spa

from rest_framework import permissions

class IsOwnerOrReadOnly(permissions.BasePermission):
    """
    Object-level permission to only allow owners of an object to edit it.
    Assumes the model instance has an `owner` attribute.
    """

    def has_object_permission(self, request, view, obj):
        # Read permissions are allowed to any request,
        # so we'll always allow GET, HEAD or OPTIONS requests.
        if request.method in permissions.SAFE_METHODS:
            return True

        # Instance must have an attribute named `owner`.
        #obj至关于数据库中的model,这里要把owner改成咱们数据库中的user
        return obj.user == request.user

这个官网有实例,直接复制过来就能够了,把其中的owner改成user便可rest

2、user_operation/viewscode

from rest_framework import viewsets
from rest_framework import mixins
from .models import UserFav
from .serializers import UserFavSerializer
from rest_framework.permissions import IsAuthenticated
from utils.permissions import IsOwnerOrReadOnly
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.authentication import SessionAuthentication

class UserFavViewset(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin):
    '''
    用户收藏
    '''
    serializer_class = UserFavSerializer
    #permission是用来作权限判断的
    # IsAuthenticated:必须登陆用户;IsOwnerOrReadOnly:必须是当前登陆的用户
    permission_classes = (IsAuthenticated,IsOwnerOrReadOnly)
    #auth使用来作用户认证的
    authentication_classes = (JSONWebTokenAuthentication,SessionAuthentication)
    #搜索的字段
    lookup_field = 'goods_id'

    def get_queryset(self):
        #只能查看当前登陆用户的收藏,不会获取全部用户的收藏
        return UserFav.objects.filter(user=self.request.user)

 

说明:jwt

  • 只有登陆用户才能够收藏
  • 用户只能获取本身的收藏,不能获取全部用户的收藏
  • JSONWebTokenAuthentication认证不该该全局配置,由于用户获取商品信息或者其它页面的时候并不须要此认证,因此这个认证只要局部中添加就能够
  • 删除settings中的'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
相关文章
相关标签/搜索