如何防止Mongoose在修改用户密码后重新设置用户密码?
很多教程都告诉我们在userSchema页面中使用bycrypt。一旦你保存了一个新的用户,它就会和加密的密码一起使用。伟大的 然而,我想,当我用一些东西编辑用户时,它也会重新设置密码,使其无法登录。你能给我一个解决方案吗?多谢各位如何防止Mongoose在修改用户密码后重新设置用户密码?,mongoose,schema,Mongoose,Schema,很多教程都告诉我们在userSchema页面中使用bycrypt。一旦你保存了一个新的用户,它就会和加密的密码一起使用。伟大的 然而,我想,当我用一些东西编辑用户时,它也会重新设置密码,使其无法登录。你能给我一个解决方案吗?多谢各位 const mongoose = require('mongoose'); const Schema = mongoose.Schema; const bcrypt = require('bcrypt-nodejs'); const eventSchema = re
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;
也许你可以检查密码是否被修改过-使用
如果你是说向上投票,不幸的是,我还不能。我的名声不够好。对不起谢谢你,救命恩人!
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();
});
});
});