【问题标题】:I am not able to serialize a user, I don't understand what happening我无法序列化用户,我不明白发生了什么
【发布时间】:2021-01-05 22:11:49
【问题描述】:

当我尝试登录我的网页时,我得到了那个错误,我在 stackoverflow 和互联网上搜索那个错误,但我无法解决这个错误。 我对此有一些疑问?

1:当我尝试记录 "user" 数据时。但它不会返回 user obj,而是返回 true。为什么?

2:在 serializeUser done 函数中,为什么我们给出参数 user.id 而不是 user._id。因为 mongodb 有 _id 字段而不是 id 字段。

错误: error image

这就是我没有终端的原因。 terminal img

代码sn-p:

passport.use(new passportLocal({
  usernameField: 'email'
}, (email, password, done) => {
  console.log(email, password);
  usermodel.findOne({
    email: email
  }, (err, user_obj) => {
    console.log("user object get by database", user_obj)
    if (err) throw new Error(err);
    if (!user_obj) {
      return done(null, false, {
        message: "There is no user with that ID."
      });
    } else if (user_obj) {
      console.log(user_obj._id)
      bcrypt.compare(password, user_obj.password, (err, varifiedUser) => {
        if (err) throw new Error(err);
        else if (varifiedUser) {
          return done(null, varifiedUser);
        } else {
          return done(null, false, {
            message: "Incorrect password!"
          });
        }
      });
    }
  });
}));

passport.serializeUser((user, done) => {
  console.log("user object serialize", user);
  done(null, user._id);
});

passport.deserializeUser((user, done) => {
  usermodel.findById(user.id, (err, id) => {
    if (!err) {
      done(null, user);
    } else {
      done(err);
    }
  });
});


router.post("/login", passport.authenticate('local', {
  successRedirect: '/auth/quiz',
  failureRedirect: '/auth/login'
}));

真的很抱歉我的语法不好。

【问题讨论】:

    标签: javascript node.js express passport.js


    【解决方案1】:

    bcrypt.compare 的第二个参数返回一个布尔值,告诉您密码是否匹配,用户数据。

    我建议将其重写为删除可选回调的作业。

    const match = bcrypt.compare(password, user_obj.password);
    if (match) return done(null, user_obj);
    

    这会将用户对象传递给serializeUser 回调。

    serializeUser 用于向req.session.passport 属性添加标识符,以便可以使用任何唯一值。我相信您可以使用 mongoose 访问 user.id 而不是 _id。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-18
      • 2018-01-27
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      • 2020-03-28
      • 2023-04-06
      • 1970-01-01
      相关资源
      最近更新 更多