第一篇StackOverflow文章,所以我开始了:我正在为我的朋友们创建一个博客。用户可以登录、发布和更新他们的配置文件。在实现了基本的用户文档(用户配置文件(更新之后,还有其他问题需要解决,发生了更令人发指的事情。我无法再使用相同的凭据登录。我尝试删除更新用户名的功能,因为我认为这是与用户登录能力相关的唯一合乎逻辑的事情,然而,即使更新图像/个人简介也会导致用户无法登录。
这是我的updateProfile((
exports.updateProfile = async (req, res, next) => {
var image = req.files.image;
const data = {};
if (req.body.username === '' || undefined) {
delete req.body.username;
} else {
data.username = req.body.username.trim();
}
if (req.body.email === '' || undefined) {
delete req.body.email;
} else {
data.email = req.body.email.trim();
}
if (req.body.bio === '' || undefined) {
delete req.body.bio;
} else {
data.bio = req.body.bio.trim();
}
let user = await User.findById(req.session.userID);
if (!data.username === false) {
await user.updateOne({ username: data.username });
}
if (!data.email === false) await user.updateOne({ email: data.email });
if (!data.bio === false) await user.updateOne({ bio: data.bio });
if (image) {
image.mv(
path.resolve(__dirname, '..', 'public/img', image.name),
async (error) => {
await user.updateOne({ image: '/img/' + image.name });
}
);
}
const updatedUser = await User.findById(req.session.userID);
user = updatedUser;
user.save(function () {
res.render('profile', {
user,
});
});
};
这是我的用户模型:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcryptjs');
var uniqueValidator = require('mongoose-unique-validator');
const validator = require('validator');
const UserSchema = new Schema({
username: {
type: String,
required: [true, 'Please provide username.'],
unique: true,
minlength: [2, 'Name must be longer than one character.'],
},
email: {
type: String,
required: [true, 'Please provide a email.'],
lowercase: true,
unique: true,
validate: [validator.isEmail, 'Please provide a valid email'],
},
password: {
type: String,
required: [true, 'Please provide password.'],
minlength: [2, 'Password must be longer than eight characters.'],
},
image: {
type: String, //PATH IN FILE SYSTEM WHERE IMAGE IS UPLOADED
default: '/img/default-user-image.png',
},
role: {
type: String,
enum: ['Neophyte', 'admin'],
default: 'Neophyte',
},
bio: {
type: String,
default: `Tell us about yourself...`,
},
});
UserSchema.plugin(uniqueValidator);
UserSchema.pre('save', function (next) {
const user = this;
bcrypt.hash(user.password, 10, (error, hash) => {
user.password = hash;
next();
});
});
const User = mongoose.model('User', UserSchema);
module.exports = User;
现在,就在我写这篇文章的时候,我相信UserSchema.pre("ve"(…是罪魁祸首。然而,因为我写了这么多,想听听社区对推荐解决方案的看法,或者告诉我我还有很长的路要走,让我知道!bcrypt是否再次通过密码重新加密导致锁定?
最好!
您可以检查密码是否被修改,只有在使用.isModified((修改密码时才能对其进行哈希
UserSchema.pre('save', function (next) {
const user = this;
if (user.isModified('password')) {
bcrypt.hash(user.password, 10, (error, hash) => {
user.password = hash;
next();
});
} else {
next();
}
});