在這裏插入代碼片
# Django REST framwork的權限驗證
一、用戶是否登錄
(1)判斷用戶是否登錄;
permission_classes = (IsAuthenticated, )
注意:permission_classes設置的是:驗證的是用戶是否登錄、用戶是否可以操作該數據等的權限
;
權限組合方式,目前支持:與&(and) 或|(or) 非~(not)
例如:permission_classes = (SecAdminPermission | AudAdminPermission,)
注意:使用元組 (SecAdminPermission | AudAdminPermission,)
或列表[ SecAdminPermission | AudAdminPermission]
都可以。
(2)設置用戶認證方式;
authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
注意:authentication_classes設置的是:用戶可以通過哪種方式登錄系統
,例如:JWT或傳統的用戶名+密碼方式登錄。
具體代碼如下:
from rest_framework.permissions import IsAuthenticated # 判斷用戶是否登錄
from rest_framework_jwt.authentication import JSONWebTokenAuthentication # jwt用戶認證
class UserFavViewset(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin,
mixins.DestroyModelMixin, viewsets.GenericViewSet):
"""
list:
獲取用戶收藏列表
retrieve:
判斷某個商品是否已經收藏
create:
收藏商品
delete:
取消收藏
"""
# 權限判斷:IsAuthenticated表示是否已經登錄,IsOwnerOrReadOnly表示數據是不是屬於當前登錄用戶
permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
# 用戶認證:方式一:JSONWebTokenAuthentication;方式二:SessionAuthentication
authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
# 定義通過哪個參數來定位實例
lookup_field = "goods_id" # 在詳細頁面時,搜索goods_id來確認該商品有沒有被收藏,是在當前用戶下進行搜索的
def get_queryset(self):
"""獲取當前登錄用戶的收藏信息"""
return UserFav.objects.filter(user=self.request.user)
# 方法一:修改商品收藏數
# def perform_create(self, serializer):
# """修改商品收藏數"""
# instance = serializer.save()
# goods = instance.goods
# goods.fav_num += 1
# goods.save()
# 動態設置序列化類
def get_serializer_class(self):
if self.action == "list":
return UserFavDetailSerializer
elif self.action == "create":
return UserFavSerializer
return UserFavSerializer
二、用戶是否對該數據有操作權限;
(1)自定義權限驗證
前提:待驗證對象有user字段;
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):
# 1 只讀
# 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
# 2 寫權限
# Instance must have an attribute named `owner`.
# return (obj.publisher if obj.publisher else self.fans )== request.user
return obj.user== request.user # 判斷當前數據是不是登錄用戶的數據
(2)在接口中,添加數據權限驗證;
class UserFavViewset(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin,
mixins.DestroyModelMixin, viewsets.GenericViewSet):
"""
list:
獲取用戶收藏列表
retrieve:
判斷某個商品是否已經收藏
create:
收藏商品
delete:
取消收藏
"""
# 權限判斷:IsAuthenticated表示是否已經登錄,IsOwnerOrReadOnly表示數據是不是屬於當前登錄用戶
permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
# 用戶認證:方式一:JSONWebTokenAuthentication;方式二:SessionAuthentication
authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
# 設置
lookup_field = "goods_id" # 在詳細頁面時,搜索goods_id來確認該商品有沒有被收藏,是在當前用戶下進行搜索的
def get_queryset(self):
"""獲取當前登錄用戶的收藏信息"""
return UserFav.objects.filter(user=self.request.user)
參考:
https://www.django-rest-framework.org/api-guide/permissions/
https://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/#adding-endpoints-for-our-user-models