这是我的变更代码,其中我使用具有名称,电子邮件,密码的User类型,并且我对注册用户和登录用户进行了两种更改。我搜索了有关graphql的所有文档,并阅读了所有与身份验证相关的博客,但无法获得从变异中返回令牌的答案
const mutation = new GraphQLObjectType({
name: "Mutation",
fields: {
addUser: {
type: UserType,
args: {
name: { type: GraphQLString },
email: { type: GraphQLString },
password: { type: GraphQLString },
avatar: { type: GraphQLString }
},
resolve(parentValue, args) {
const avatar = gravatar.url(args.email);
return bcrypt
.hash(args.password, 10)
.then(hash => {
args.password = hash;
const newUser = new User({
name: args.name,
email: args.email,
password: args.password,
avatar
});
return newUser
.save()
.then(user => user)
.catch(e => e);
})
.catch(e => e);
}
},
login: {
name: "Login",
type: UserType,
args: {
email: { type: GraphQLString },
password: { type: GraphQLString }
},
resolve(parentValue, args, context) {
return User.findOne({ email: args.email })
.then(user => {
if (user) {
return bcrypt
.compare(args.password, user.password)
.then(isValid => {
if (!isValid) {
throw new Error({ message: "password Incrrect" });
} else {
const token = jwt.sign(
{ name: user.name, id: user.id },
"mySecret"
);
return user;
}
})
.catch(e => e);
} else {
throw new Error({ message: "email Incorrect" });
}
})
.catch(e => e);
}
}
}
});
这是我的用户类型
const UserType = new GraphQLObjectType({
name: "User",
fields: {
id: { type: GraphQLString },
name: { type: GraphQLString },
email: { type: GraphQLString },
password: { type: GraphQLString },
avatar: { type: GraphQLString }
}
});
答案 0 :(得分:2)
我建议您通过删除密码字段并添加令牌字段来更新UserType
,例如:
const UserType = new GraphQLObjectType({
name: "User",
fields: {
id: { type: GraphQLString },
name: { type: GraphQLString },
email: { type: GraphQLString },
avatar: { type: GraphQLString },
token: { type: GraphQLString }
}
});
原因是UserType
是突变的返回类型,因此它是“ public”,也许我们不应该向public发送密码(因为我们在服务器端进行身份验证),但是JWT是公开,所以我们可以将其发回。
然后在您的login
变体中,将令牌添加到用户对象中,例如:
login: {
name: "Login",
type: UserType,
args: { email: { type: GraphQLString }, password: { type: GraphQLString } },
resolve(parentValue, args, context) {
return User.findOne({ email: args.email })
.then(user => {
.........
const token = jwt.sign(
{ name: user.name, id: user.id },
"mySecret"
);
user.token = token;
return user;
}
........
}
}