I'm creating an admin panel where user can register, login and update his information. While registering user information, I used bcrypt
library to encrypt and store password in MongoDb. But when I get user information to put it in update form, its giving me a long encrypted password.
I want to show original password so user can see and update password:
Add User Function:
// Add USER
export const addUser = async (req, res) => {
try {
const {
name,
email,
password,
picturePath,
country,
role,
} = req.body;
const salt = await bcrypt.genSalt();
const passwordHash = await bcrypt.hash(password, salt);
const newUser = new User({
name,
email,
password: passwordHash,
picturePath,
country,
role
});
const savedUser = await newUser.save();
res.status(201).json(savedUser);
} catch (err) {
res.status(500).json({ error: err.message });
}
}
Update user:
// UPDATE USER
export const updateUser = async (req, res) => {
try {
const { id, name, email, password, country, picturePath, role } = req.body;
const Updateuser = await User.updateOne({"_id": id}, {$set: {
name: name,
email: email,
country: country,
password: password,
picturePath: picturePath,
role: role
}});
const user = await User.findById(id);
const token = jwt.sign({ id: id }, process.env.JWT_SECRET);
res.status(200).json({token, user});
} catch (error) {
res.status(400).json({message: error.message});
}
}
CodePudding user response:
Hashing is one way. You cannot reverse a hash to the original string (nor should you want to, it would defeat the whole point of hashing). To update a user's password, all you need is the user id and the new password. It could be written as follows:
const { id, password } = req.body;
// hash the new password just as you do when you creating a new user
const passwordHash = await bcrypt.hash(password, salt);
const updatedUser = await User.findByIdAndUpdate(id, { password: passwordHash })
This should correctly update your User with the new password, leaving the other fields untouched.
EDIT: Typically, as a mean of additional security, you would authenticate the user again (ask for old password and check it) before updating to the new password.