mongoose - 如何防止 Mongoose 在修改用户后重新散列用户密码?

标签 mongoose schema

许多教程告诉您在您的 userSchema 页面中使用 bycrypt。保存新用户后,它会附带加密密码。伟大的。 然而,我想,当我用某些东西编辑用户时,它也会重新哈希密码,导致无法登录。你能给我一个解决方案吗?谢谢。

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt-nodejs');
const eventSchema = require('./eventSchema');

const userSchema = new Schema({
  email: { type: String, unique: true, lowercase: true },
  password: String,
  eventList: [{ 
    type: Schema.ObjectId, 
    ref: "event"
  }],
  administrator: { type: Boolean, default: false }
});

// On Save Hook, encrypt password
// Before saving a model, run this function
userSchema.pre('save', function(next) {
  // get access to the user model
  const user = this;

  // generate a salt then run callback
  bcrypt.genSalt(10, function(err, salt) {
    if (err) { return next(err); }

    // hash (encrypt) our password using the salt
    bcrypt.hash(user.password, salt, null, function(err, hash) {
      if (err) { return next(err); }

      // overwrite plain text password with encrypted password
      user.password = hash;
      next();
    });
  });
});

userSchema.methods.comparePassword = function(candidatePassword, callback) {
  bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
    if (err) { return callback(err); }

    callback(null, isMatch);
  });
};
// Create the model class
const ModelClass = mongoose.model('user', userSchema);

// Export the model
module.exports = ModelClass;

最佳答案

也许你可以检查密码是否被修改 - 使用isModified .

userSchema.pre('save', function(next) {
    const user = this;
    if (!user.isModified('password')) return next();

    bcrypt.genSalt(10, function(err, salt) {
        if (err) return next(err);
        bcrypt.hash(user.password, salt, null, function(err, hash) {
            if (err) return next(err);
            user.password = hash;
            next();
        });
    });
});

关于mongoose - 如何防止 Mongoose 在修改用户后重新散列用户密码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43706606/

相关文章:

ios - iOS 应用内购买交易 ID 是否始终为长整数?

Schema.org ProfessionalService 是否已弃用?

mongodb - 如何在不创建 Mongoose 模型的情况下将 GraphQL 与 Mongoose 和 MongoDB 结合使用

node.js - 更新文档时在非对象上调用 TypeError : Object. 键

Gorm AutoMigrate() 和 CreateTable() 不工作

sql-server-2005 - 如何查询数据库模式是否存在

xml - 如何从 XSD 模式生成一组测试 XML 数据文件?

javascript - 用户 findOne 不工作

javascript - 嵌套数组内的 Mongoose findOneAndUpdate

javascript - Mongoosejs .find 返回整个模型而不是文档