Первый пост в StackOverflow, поэтому я go: я создаю блог для своих друзей. Пользователи могут входить в систему, публиковать и обновлять свои профили. После внедрения обновления базового c пользовательского документа (профиля пользователя), в котором все еще есть другие проблемы, которые необходимо решить, произошло нечто более отвратительное. Я больше не могу войти в систему с теми же учетными данными. Я попытался удалить возможность обновления имени пользователя, потому что думал, что это единственная логическая вещь, связанная с возможностью этого пользователя войти в систему, однако даже обновление изображения / биографии приведет к тому, что пользователь не сможет войти в систему.
Вот мой 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 ('save ') ... виноват. Однако, поскольку я написал так много и хотел бы услышать от сообщества, что они думают о рекомендуемых решениях, или сказать мне, что я далеко, дайте мне знать! Не вызывает ли повторное шифрование bcrypt пароля снова блокировку?
Лучшее!