bcryptjs 在存储到 mongodb 之前不加密密码并保存纯文本

问题描述 投票:0回答:2

我使用 bcryptjs 在存储到 mongodb 之前对密码进行哈希处理,但它将密码存储为明文(无哈希)。这是我的 userModel.js

const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");

const userSchema = new mongoose.Schema(
  {
 
    mobile: {
      type: String,
    },
    password: {
      type: String,
    },
   
  },
  { timestamps: true }
);

userSchema.methods.matchPassword = async function (enteredPassword) {
  return await bcrypt.compare(enteredPassword, this.password);
};

userSchema.pre("save", async function (next) {
  console.log("pre save called");
  if (!this.isModified("password")) {
    next();
  }
  const salt = await bcrypt.genSalt(10);
  this.password = bcrypt.hash(this.password, salt);
});

const User = mongoose.model("User", userSchema);

module.exports = User;

我的注册控制器是这样写的

module.exports.register = asynchandler(async (req, res) => {
  const {  mobile, password } = req.body;
  const user = await User.findOne({ mobile });
  if (user) {
    res.status(400).json({ message: "user already exists" });
  } else {
    const newUser = await User.create({
      mobile,
      password,
   });
   res.status(200).json(newUser);
  }
});
但是当我使用保存为明文(无哈希)的邮递员密码测试 API 时

node.js mongodb hash bcrypt bcryptjs
2个回答
0
投票

我终于找到了解决方案。我不知道为什么但是使用下面的代码工作正常

userSchema.pre("save", async function (next) {
  if (!this.isModified("password")) {
    next();
  }
  bcrypt.hash(this.password, 10, (err, hash) => {
    if (err) {
      console.log("something went wrong for hashing");
    }
    if (hash) {
      this.password = hash;
    }
  });
});


0
投票

你不需要在注册控制器中添加密码,

module.exports.register = asynchandler(async (req, res) => {
  const {  mobile, password } = req.body;
  const user = await User.findOne({ mobile });
  if (user) {
    res.status(400).json({ message: "user already exists" });
  } else {
    const newUser = await User.create({
      mobile,
   });
   res.status(200).json(newUser);
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.