權限組件
源碼
權限組件的源碼執行過程和之前的認證組件是相同的,如下:
self.check_permissions(request)
def check_permissions(self, request):
"""
Check if the request should be permitted.
Raises an appropriate exception if the request is not permitted.
"""
for permission in self.get_permissions():
if not permission.has_permission(request, self):
self.permission_denied(
request, message=getattr(permission, 'message', None)
)
思考:如果要做權限認證,我們首先要知道當前登錄的用戶是誰,那麼我們如何知道呢?
首先rest_framework中的三個組件是按順序執行的:#認證組件 self.perform_authentication(request) #權限組件 self.check_permissions(request) #頻率組件 self.check_throttles(request)
在第一個執行的認證組件源碼中有這樣一段代碼
self.user, self.auth = user_auth_tuple
這個user_auth_tuple恰巧就是我們自定義認證視圖時返回的那個元祖
class TokenAuth(BaseAuthentication): def authenticate(self, request): ...... return token_obj.user, token_obj.token #需要返回一個元組
因此此時的self.user=token_obj.user,self.auth=token_obj.token
局部視圖權限
在app01.service.permissions.py中:
from rest_framework.permissions import BasePermission
class SVIPPermission(BasePermission):
message = "SVIP才能訪問" #沒通過驗證則返回錯誤
def has_permission(self, request, view): #固定寫法
if request.user.user_type == 3:
return True
return False
在views.py:
class AuthorView(viewsets.ModelViewSet):
authentication_classes = [TokenAuth,]
permission_classes = [SVIPPermission,]
queryset = Author.objects.all()
serializer_class = AuthorModelSerializers
全局視圖權限
REST_FRAMEWORK={
"DEFAULT_AUTHENTICATION_CLASSES":["app01.service.auth.Authentication",],
"DEFAULT_PERMISSION_CLASSES":["app01.service.permissions.SVIPPermission",]
}