我试图在用户注册时自动登录用户,而不是重定向到登录页面然后只登录。但是,我收到一个错误
"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.'])
如果我直接登录,那么它可以工作,但如果我想在注册用户时登录,那么它不起作用,所以我在注册用户时无法传递令牌。
注册时如何自动登录用户以便传递令牌?