如何在nodejs中更新bcrypt密码?

时间:2019-07-09 09:05:07

标签: node.js express jwt bcrypt

所以我有这台路由器,当管理员添加新职员时,密码会被散列,因此在添加/职员路由中可以很好地工作,但是当管理员尝试更新密码时,密码不再会散列,而且当该用户时使用该新密码登录时,总是显示密码不正确(很明显是我定义的),有人可以帮助我吗?

//Adding the staff which works perfectly fine   
router.post(
      "/add/staff",
      passport.authenticate("jwt", { session: false }),
      (req, res) => {
        if (req.user.isAdmin === true) {
          const newUser = new User({
            name: req.body.name,
            email: req.body.email,
            role: req.body.role,
            password: req.body.password
          });
          if (req.body.adminCode === "admin123") {
            newUser.isAdmin = true;
          }
          bcrypt.genSalt(10, (err, salt) => {
            bcrypt.hash(newUser.password, salt, (err, hash) => {
              if (err) {
                res.json({ success: false, msg: "Failed to add user" });
              } else {
                newUser.password = hash;
                newUser
                  .save()
                  .then(user => {
                    res.json({ success: true, msg: "User added" });
                  })
                  .catch(ex => {
                    return res.status(500).send("Something went wrong");
                  });
              }
            });
          });
        } else {
          return res.json("Acess denied");
        }
      }
    );



//The update route which does not hash the password 
    router.put(
  "/update/:id",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    if (req.user.isAdmin === true) {
      User.update(
        { _id: req.params.id },
        {
          name: req.body.name,
          email: req.body.email,
          role: req.body.role,
          password: req.body.password,
          password2: req.body.password2
        }
      )
        .then(success => res.json({ msg: "Updated Successfully" }))
        .catch(err => res.json(err));
    }
  }
);

我也正在使用护照和jwt

const JwtStrategy = require("passport-jwt").Strategy;
const ExtractJwt = require("passport-jwt").ExtractJwt;
const mongoose = require("mongoose");
const User = mongoose.model("users");
const keys = require("./dbSecretKeys");

let opts = {};
// opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme("jwt");
opts.secretOrKey = keys.secretOrKey;

module.exports = passport => {
  passport.use(
    new JwtStrategy(opts, (jwt_payload, done) => {
      User.findById(jwt_payload.id)
        .then(user => {
          if (user) {
            return done(null, user);
          }
          return done(null, false);
        })
        .catch(err => console.log(err));
    })
  );
};

这是我尝试过的

router.put(
  "/update/:id",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    if (req.user.isAdmin === true) {
      User.updateOne(
        { _id: req.params.id },
        {
          name: req.body.name,
          email: req.body.email,
          role: req.body.role,
          password: req.body.password
        }
      )
        .then(userUpdateData => {
          bcrypt.genSalt(10, (err, salt) => {
            bcrypt.hash(userUpdateData.password, salt, (err, hash) => {
              if (err) {
                res.json({ success: false, msg: "Failed to update user" });
              } else {
                userUpdateData.password = hash;
                userUpdateData
                  .save()
                  .then(user => {
                    res.json({ success: true, msg: "User updated" });
                  })
                  .catch(ex => {
                    return res.status(500).send("Something went wrong");
                  });
              }
            });
          });
        })
        .catch(err => res.json(err));
    } else {
      return res.json("Access Denied");
    }
  }
);

0 个答案:

没有答案