passport-local-mongoose changePassword功能

时间:2017-09-04 22:25:00

标签: node.js mongodb authentication passport-local

我想拥有用户可以更改密码的功能。 我已经实现了一条路线(' / resetPasswd' ),如下所示:

UserRouter.route('/resetPasswd')

.post(function (req, res, next) {
    passport.authenticate('local', function (err, user, info) {
        user.changePassword(req.body.oldPassword, req.body.newPassword, function (err, user) {
            if (err) next(err);
            res.json('password changes successfully !');
        })
    })(req, res, next);
});

这是我发送的身体:

{
    "oldpassword": "secret",
    "newPassword": "new"
}

但是我将此错误视为回复:

{
   "message": "user.changePassword is not a function",
   "error": {}
}

这是我的架构图片:

用户架构:

user schema

我不认为我应该在我的架构中声明 changePassword 功能(因为它是由 passport-local-mongoose 提供的,尽管我添加了它但仍然得到同样的错误)我在这里犯了什么错误?

3 个答案:

答案 0 :(得分:1)

实际上昨晚有人有同样的问题。他们的问题是需要更新的包。我会检查你是否使用了最新版本。

答案 1 :(得分:1)

由于changePassword是一种模式方法,因此必须在模型的实例上使用它,而不是模型本身或导入的PassportLocalMongoose。

UserModel.findById(req.user._id) 
// I assume you already have authentication and the req.user is generated
        .then(foundUser => {
            foundUser.changePassword(req.body.old, req.body.new)
                .then(() => {
                    console.log('password changed');
                })
                .catch((error) => {
                    console.log(error);
                })
        })
        .catch((error) => {
            console.log(error);
        });

通过回调函数发送的用户对象护照只是一个对象,而不是模式实例文档对象,因此它没有changePassword函数。

答案 2 :(得分:0)

这是我在控制器中处理重置密码的操作,

exports.editPassword = async (req, res) => {
  const user = await User.findOne({
    username: req.user.username
});
await user.setPassword(req.body.password);
const updatedUser = await user.save();
req.login(updatedUser);
req.flash('success', 'Password Changed Successfully') res.redirect('back')
}

从文档Passport-local-mongoose中,您首先需要让特定用户更新密码,在本例中为当前登录用户,该用户可以在 req.user 上找到。我们接触到了,您可以使用任何return属性来查询您的集合,使用async await我创建了一个变量来保存返回对象,在我的情况下为“ user”,此后我将setProperty链接到它上,并传入新密码(req.body.password),因为它返回了一个promise,所以我等待它并为其分配一个变量。从这里开始,您是个好人。...注意:由于这是一个承诺,它可以解决拒绝问题,因此可以通过将代码放在安全的try..catch中来完成处理错误。您可以阅读更多Here