1. 程式人生 > >REST framework組件-認證、權限、限制

REST framework組件-認證、權限、限制

style miss sca cat rfi return ria serial quest

認證

定義user表和token表

class UserInfo(models.Model):
    username = models.CharField(verbose_name=用戶名, max_length=32)
    pwd = models.CharField(max_length=64)
    type = models.SmallIntegerField(
        choices=((1, 普通用戶), (2, VIP用戶)),
        default=1
    )


class UserToken(models.Model):
    user 
= models.OneToOneField(to=UserInfo,on_delete=models.CASCADE) token = models.CharField(max_length=64)

定義一個登錄視圖

class AuthView(APIView):
    def post(self, request, *args, **kwargs):
        ret = {code: 1000}
        username = request.data.get(username)
        pwd = request.data.get(pwd)
        
print(username, pwd) user = models.UserInfo.objects.filter(username=username, pwd=pwd).first() if not user: ret[code] = 1001 ret[error] = 用戶名或密碼錯誤 else: token = uuid.uuid4() models.UserToken.objects.update_or_create(user=user, defaults={
token: token}) ret[token] = str(token) return Response(ret)

定義一個認證類

class MyAuth(BaseAuthentication):
    def authenticate(self, request):
        if request.method in ["POST", "PUT", "DELETE"]: #認證post等方法
            request_token = request.data.get("token", None)
        elif request.method in [GET]:     #認證get方法
            request_token = request.query_params.get(token, None)
        else:
            return None, None
        if not request_token:
            raise AuthenticationFailed(缺少token)
        token_obj = models.UserToken.objects.filter(token=request_token).first()
        if not token_obj:
            raise AuthenticationFailed(無效的token)
        return token_obj.user.username, token_obj

視圖級別認證

class BookViewSet(viewsets.ModelViewSet):
    #認證類
    authentication_classes = [MyAuth, ]

    queryset = Book.objects.all()
    serializer_class = BookSerializers

全局級別認證

# 在settings.py中配置
REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": ["api.auth.auth.MyAuth", ]
}

權限

自定義一個權限類

class MyPermission(BasePermission):
    message = VIP用戶才能訪問
    def has_permission(self, request, view):
        """
        自定義權限只有VIP用戶才能訪問
        """
        # 因為在進行權限判斷之前已經做了認證判斷,所以這裏可以直接拿到request.user
        if request.user and request.user.type == 2:  # 如果是VIP用戶
            return True
        else:
            return False

視圖級別配置

class BookViewsSet(viewsets.ModelViewSet): 
    authentication_classes = [MyAuth, ]
    # 權限
    permission_classes = [MyPermission, ]

    queryset = Book.objects.all()
    serializer_class = BookModelSerializer

全局級別設置

# 在settings.py中設置rest framework相關配置項
REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": ["api.auth.auth.MyAuth", ],
    "DEFAULT_PERMISSION_CLASSES": ["api.auth.auth.MyPermission", ]
}

限制(待續)

REST framework組件-認證、權限、限制