Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 无法使用提供的凭据登录_Python_Django_Django Rest Framework_Django Authentication_Graphene Django - Fatal编程技术网

Python 无法使用提供的凭据登录

Python 无法使用提供的凭据登录,python,django,django-rest-framework,django-authentication,graphene-django,Python,Django,Django Rest Framework,Django Authentication,Graphene Django,我尝试在用户注册时自动登录用户,而不是重定向到登录页面,然后只登录。然而,我得到了一个错误 "errors": [ "email", "Unable to login with provided credentials." ], 以下是我所做的: def get_token(**user): data = {} if user.get('email') and user.get('password'): serializer = JSONWebTok

我尝试在用户注册时自动登录用户,而不是重定向到登录页面,然后只登录。然而,我得到了一个错误

"errors": [
   "email",
   "Unable to login with provided credentials."
],
以下是我所做的:

def get_token(**user):
    data = {}
    if user.get('email') and user.get('password'):
        serializer = JSONWebTokenSerializer(data=user)
        if serializer.is_valid():
            token = serializer.object['token']
            user = serializer.object['user']
            data = {
                'user': user,
                'token': token
            }
            return data
        else:
            data = {
                'errors': serializer.errors
            }
            return data
    data = {
        'errors': 'Email or Password not provided'
    }
    return data

# creates the user but could not login
class Register(graphene.Mutation):
    '''
        Mutation to register a user
    '''
    class Arguments:
        email = graphene.String(required=True)
        password = graphene.String(required=True)
        password_repeat = graphene.String(required=True)

    success = graphene.Boolean()
    token = graphene.String()
    user = graphene.Field(UserQuery)
    errors = graphene.List(graphene.String)

    def mutate(self, info, email, password, password_repeat):
        if password == password_repeat:
            try:
                serializer = RegistrationSerializer(data={
                    'email': email,
                    'password': password,
                    'is_active': False
                })
                if serializer.is_valid():
                    user = serializer.save()
                    user_identity = get_token(email=user.email, password=user.password)
                    if not user_identity.get('errors'):
                        return Register(success=True, user=user_identity.get('user'), token=user_identity.get('token'))
                    else:
                        return Register(success=False, token=None, errors=['email', 'Unable to login with provided credentials.'])
            except Exception as e:
                errors = [e]
                return Register(success=False, errors=errors)
            errors = ["password", "Passwords don't match."]
            return Register(success=False, errors=errors)


# this works
class Login(graphene.Mutation):
    """
    Mutation to login a user
    """
    class Arguments:
        email = graphene.String(required=True)
        password = graphene.String(required=True)

    success = graphene.Boolean()
    errors = graphene.List(graphene.String)
    token = graphene.String()
    user = graphene.Field(UserQuery)

    def mutate(self, info, email, password):
        user_identity = get_token(email=email, password=password)
        if not user_identity.get('errors'):
            return Login(success=True, user=user_identity.get('user'), token=user_identity.get('token'))
        else:
            return Login(success=False, token=None, errors=['email', 'Unable to login with provided credentials.'])
如果我直接登录,那么它可以工作,但是如果我想在注册用户时登录,那么它不工作,因此在注册用户时我无法传递令牌


如何在注册时自动登录用户,以便传递令牌?

一个可能的原因是您正在将新创建的用户对象更改为
不活动

在代码中,您可以看到您正在将新创建的用户定义为非活动用户

serializer = RegistrationSerializer(data={
    'email': email,
    'password': password,
    'is_active': False
})
处于活动状态:False
表示用户名和密码可能有效,但您的帐户被禁用,这就是您无法在注册期间登录的原因

此外,如果可以看到您所依赖的
JSONWebTokenSerializer
的源代码,则在验证函数中,它将检查用户是否处于非活动状态,然后抛出一个错误

这是源代码 因此,我可以看到的一个解决方案是将
is_active
标志变为true或remove
is_active:False,它将起作用

def validate(self, attrs):
        credentials = {
            self.username_field: attrs.get(self.username_field),
            'password': attrs.get('password')
        }

        if all(credentials.values()):
            user = authenticate(**credentials)

            if user:
                if not user.is_active:
                    msg = _('User account is disabled.')
                    raise serializers.ValidationError(msg)

                payload = jwt_payload_handler(user)

                return {
                    'token': jwt_encode_handler(payload),
                    'user': user
                }
            else:
                msg = _('Unable to log in with provided credentials.')
                raise serializers.ValidationError(msg)
        else:
            msg = _('Must include "{username_field}" and "password".')
            msg = msg.format(username_field=self.username_field)
            raise serializers.ValidationError(msg)