Django-太多值无法解包(预期2)

时间:2020-10-24 09:16:11

标签: python django

我正在尝试创建一个自定义后端,其中用户使用私钥和私钥来查看我使用Django Rest Framework创建的API端点。我已经知道这不是安全性方面的最佳选择,但是由于端点仅用于查看数据(它仅具有GET方法),因此在这里没什么大不了的。

这是我的代码:

class TokenMiddleware(AuthenticationMiddleware):
    def process_request(self, request):
        try:
            token = request.GET[TOKEN_QUERY_PUBLIC]
            secret = request.GET[TOKEN_QUERY_SECRET]
        except KeyError:
            raise ValidationError(detail="Missing parameter in auth")

        user = auth.authenticate(request, token=token, secret=secret)
        if user:
            # The token is valid. Save the user to the request and session.
            request.user = user
            auth.login(request, user)
        else:
            raise ValidationError(detail="AUTH FAILED")

class TokenBackend(ModelBackend):
    def authenticate(self, request, token=None, secret=None):
        if not token:
            return None

        try:
            publicQuery = User.objects.get(api_keys__public=token)
            if publicQuery != None:
                privateQuery = Api_keys.objects.get(public=token, secret=secret)
                if privateQuery.secret == secret:
                    return User.objects.get(username=publicQuery)
                else:
                    return None
            else:
                return None
        except User.DoesNotExist:
            # A user with that token does not exist
            return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

这是Api_keys模型:

class Api_keys(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    public = models.CharField(max_length=30, blank=True)
    secret = models.CharField(max_length=30, blank=True)

此代码的问题是,每次我尝试进行身份验证时,都会出现以下错误:

too many values to unpack (expected 2)

更多详细信息:

File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\request.py", line 220, in user
  self._authenticate()
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\request.py", line 380, in _authenticate
  self.user, self.auth = user_auth_tuple

我的进口货

from django.contrib import auth
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from django.contrib.auth.middleware import AuthenticationMiddleware
from rest_framework.exceptions import ValidationError
from api.models import Api_keys

问题应该在第auth.login(request, user)行之后,直到我看到返回的有效用户为止。任何帮助都将不胜感激!

0 个答案:

没有答案