DRF的权限认证
一、自定义权限
utils文件夹下新建permissions.py,代码如下:
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即可
二、user_operation/views
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)
说明:
- 只有登录用户才可以收藏
- 用户只能获取自己的收藏,不能获取所有用户的收藏
- JSONWebTokenAuthentication认证不应该全局配置,因为用户获取商品信息或者其它页面的时候并不需要此认证,所以这个认证只要局部中添加就可以
- 删除settings中的'rest_framework_jwt.authentication.JSONWebTokenAuthentication',