【问题标题】:change password in nodejs, mongoDB with passport使用护照更改nodejs,mongoDB中的密码
【发布时间】:2018-08-27 05:08:46
【问题描述】:

我在我的应用程序中使用带有 Passport 的 JWT 进行身份验证,但我不知道如何更改密码。

这是我的登录功能:

function login(req, res, next) {
    const userObj = {
        email: req.body.email,
        userType: req.body.userType
    };
    UserSchema.findOneAsync(userObj, '+password')
        .then((user) => {
        if (!user) {
            const err = new APIError('User not found with the given email id', httpStatus.NOT_FOUND);
            return next(err);
        } else {
            user.comparePassword(req.body.password, (passwordError, isMatch) => {
            if (passwordError || !isMatch) {
                const err = new APIError('Incorrect password', httpStatus.UNAUTHORIZED);
                return next(err);
            }
            user.loginStatus = true;
            user.gpsLoc = [19.02172902354515, 72.85368273308545];
            const token = jwt.sign(user, config.jwtSecret);
            UserSchema.findOneAndUpdateAsync({ _id: user._id }, { $set: user }, { new: true })
                .then((updatedUser) => {
                const returnObj = {
                    success: true,
                    message: 'user successfully logged in',
                    data: {
                    jwtAccessToken: `JWT ${token}`,
                    user: updatedUser
                    }
                };
                res.json(returnObj);
                })
                .error((err123) => {
                const err = new APIError(`error in updating user details while login ${err123}`, httpStatus.INTERNAL_SERVER_ERROR);
                next(err);
                });
            });
        }
    })
    .error((e) => {
        const err = new APIError(`erro while finding user ${e}`, httpStatus.INTERNAL_SERVER_ERROR);
        next(err);
    });
}

我的用户数据库是这样的。

import Promise from 'bluebird';
import mongoose from 'mongoose';
import httpStatus from 'http-status';
import APIError from '../helpers/APIError';
import bcrypt from 'bcrypt';

const UserSchema = new mongoose.Schema({
    fname: { type: String, default: null },
    lname: { type: String, default: null },
    email: { type: String, required: true, unique: true },
    password: { type: String, required: true, select: false },
});

UserSchema.pre('save', function userSchemaPre(next) {
    const user = this;
    if (this.isModified('password') || this.isNew) {
        bcrypt.genSalt(10, (err, salt) => {
        if (err) {
            return next(err);
        }
        bcrypt.hash(user.password, salt, (hashErr, hash) => {
            if (hashErr) {
            return next(hashErr);
            }
            user.password = hash;
            next();
        });
        });
    } else {
        return next();
    }
});

UserSchema.methods.comparePassword = function comparePassword(pw, cb) {
    const that = this;
    bcrypt.compare(pw, that.password, (err, isMatch) => {
        if (err) {
        return cb(err);
        }
        cb(null, isMatch);
    });
};

我已经做了另一个重置密码的功能,并且匹配检查的旧密码像登录功能一样有效,现在我想在数据库中更新新护照。我该怎么做?

非常感谢

【问题讨论】:

    标签: node.js mongodb passwords passport.js passport-local


    【解决方案1】:

    我不确定您在此处寻找什么,但 changePassword 函数只是对 UserSchema 的简单更新。这是一个示例:

    function changePassword(req, res, next) {
    
    
    // Init Variables
      var passwordDetails = req.body;
    
      if (req.user) {
        if (passwordDetails.newPassword) {
          UserSchema.findById(req.user.id, function (err, user) {
            if (!err && user) {
              if (user.authenticate(passwordDetails.currentPassword)) {
                if (passwordDetails.newPassword === passwordDetails.verifyPassword) {
                  user.password = passwordDetails.newPassword;
    
                  user.save(function (err) {
                    if (err) {
                      return res.status(422).send({
                        message: errorHandler.getErrorMessage(err)
                      });
                    } else {
                      req.login(user, function (err) {
                        if (err) {
                          res.status(400).send(err);
                        } else {
                          res.send({
                            message: 'Password changed successfully'
                          });
                        }
                      });
                    }
                  });
                } else {
                  res.status(422).send({
                    message: 'Passwords do not match'
                  });
                }
              } else {
                res.status(422).send({
                  message: 'Current password is incorrect'
                });
              }
            } else {
              res.status(400).send({
                message: 'User is not found'
              });
            }
          });
        } else {
          res.status(422).send({
            message: 'Please provide a new password'
          });
        }
      } else {
        res.status(401).send({
          message: 'User is not signed in'
        });
      }
    };
    

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      您不必在模式中编写任何方法。您可以直接将 ChangePassword 函数与这样的架构一起使用

       user.changePassword(req.body.oldpassword, req.body.newpassword, function(err) 
         {
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-12
        • 1970-01-01
        • 2021-03-25
        • 2021-02-10
        • 1970-01-01
        • 2017-11-29
        • 2019-12-05
        • 1970-01-01
        相关资源
        最近更新 更多