Untitled
unknown
plain_text
a year ago
1.6 kB
6
Indexable
// Change Password
router.post('/change-password', auth, async(req, res) => {
try {
const { currentPassword, newPassword, confirmPassword } = req.body;
const userId = req.user.id;
// Validate input
if (!currentPassword || !newPassword || !confirmPassword) {
return res.status(400).json({ error: 'Current password, new password, and confirm password are required' });
}
if (newPassword !== confirmPassword) {
return res.status(400).json({ error: 'New password and confirm password do not match' });
}
// Fetch the user
const user = await UserLogin.findOne({ where: { id: userId } });
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
// Verify current password
const validPassword = await bcrypt.compare(currentPassword, user.password);
if (!validPassword) {
return res.status(401).json({ error: 'Current password is incorrect' });
}
// Hash the new password
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(newPassword, salt);
// Update the user's password
await UserLogin.update({ password: hashedPassword }, { where: { id: userId } });
res.status(200).json({ message: 'Password changed successfully' });
} catch (error) {
console.error('Change password error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});Editor is loading...
Leave a Comment