我正在使用graphql进行注册/登录。注册运行顺利,但我在重新登录时遇到了bcrypt错误。当我在loginUser函数下面的if语句中将其更改为user.password时,它会说抛出一个newUser is undefined错误。我的错误在哪里?
解析程序:
const resolvers = {
Mutation: {
async registerUser(_, { registerInput: { username, email, password } }) {
const previousUser = await User.findOne({ email });
if (previousUser) {
throw new ApolloError(
"A user with this email already exists" + email,
"User_Already_Exists"
);
}
var encryptedPassword = await bcrypt.hash(password, 10);
const newUser = new User({
username: username,
email: email.toLowerCase(),
password: encryptedPassword,
});
const token = jwt.sign(
{ user_id: newUser._id, email },
"this is the secret",
{
expiresIn: "2h",
}
);
newUser.token = token;
const res = await newUser.save();
return {
id: res.id,
...res._doc,
};
},
async loginUser(_, { loginInput: { email, password } }) {
const user = await User.findOne({ email });
if (user && (await bcrypt.compare(password, user.model))) {
const token = jwt.sign(
{ user_id: newUser._id, email },
"this is the secret",
{
expiresIn: "2h",
}
);
user.token = token;
return {
id: res.id,
...res._doc,
};
- 您需要比较
user.password
而不是user.model
- 如果密码匹配,则未定义
newUser
,请改用user
async loginUser(_, { loginInput: { email, password } }) {
const user = await User.findOne({ email });
if (user && (await bcrypt.compare(password, user.password))) {
const token = jwt.sign(
{ user_id: user._id, email },
"this is the secret",
{ expiresIn: "2h"}
);
user.token = token; // this isn't used anywhere, why?
return {id: res.id,...res._doc}; // this looks wrong too, res is not in scope
}
}