身份验证返回 None 而不是用户

时间:2021-07-19 19:37:37

标签: python django django-rest-framework

我目前正在开发我的 Django 应用。场景是我创建了一个自定义用户模型。我的用户模型的代码如下:

...
class User(AbstractBaseUser, PermissionsMixin):
    """Custom user model that supports using email instead of username"""
    email = models.EmailField(max_length=255, unique=True)
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    is_active = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'

我自定义了 User 模型,以根据 email 而不是用户名对用户进行身份验证。我之前已经这样做了,但不知道何时尝试验证 token 的用户,它返回 None。这里我使用 rest_framework.authtoken 来进行 TokenAuthentication,这是我的序列化程序代码:

...
class AuthTokenSerializer(serializers.Serializer):
    """Serializer for the user authentication object"""
    email = serializers.CharField()
    password = serializers.CharField(
        style={'input_type': 'password'},
        trim_whitespace=False
    )

    def validate(self, attrs):
        """Validate and authenticate the user"""
        email = attrs.get('email')
        password = attrs.get('password')

        user = authenticate(
            request=self.context.get('request'),
            username=email,
            password=password
        )
        if not user:
            msg = _('Unable to authenticate with provided credentials')
            raise serializers.ValidationError(msg, code='authentication')

        attrs['user'] = user
        return attrs

嗯!感谢断点。我已经弄清楚实际错误发生在哪里。我在 authenticate() 中发现了一个错误,它总是返回 None 而不是 User 对象,即使所有凭据都正确。

注意:我已经使用电子邮件和用户名这两个参数测试了 authenticate

而且,我已经自定义了 BaseUserManager 类并使用我的 create_user() 方法覆盖以创建自定义用户:

def create_user(self, email, password=None, **kwargs):
        """To create user using an email instead
            of username"""
        if not email:
            raise ValueError('Invalid Email!!')
        user = self.model(email=self.normalize_email(email), **kwargs)
        user.set_password(password)
        user.save(using=self._db)

        return user

这是我的代码每次都失败的测试用例。

def test_create_token_for_user(self):
        """Test that a token is created for the user"""
        payload = {'email': 'test@domain.com', 'password': 'testpass'}
        create_user(**payload)
        res = self.client.post(TOKEN_URL, payload)

        self.assertIn('token', res.data)
        self.assertEqual(res.status_code, status.HTTP_200_OK)

它说token not found in ....。这是因为 authenticate() 函数返回 None 而不是用户对象。

1 个答案:

答案 0 :(得分:1)

感谢@harryghgim 帮助我。错误现在基本上解决了,使用authenticate()函数时有一个概念。如果 user.is_active = False,它返回 None。当您要使用身份验证时,请确保您的 is_active 为 True。它仅适用于活跃用户。