Vicky Gonsalves Vicky Gonsalves - 1 year ago 202
Node.js Question

Implement change password with Loopback

I am trying to implement the change password feature with Loopback's built-in method, It works fine, but it doesn't update the password with

instead it just saves a plain text in the db. I am using
npm package in this project. I have searched many sites but I am unable to find the proper way to implement this feature. Does anyone have idea how to do this?

//Change user's pasword'/change-password', function(req, res, next) {
var User = app.models.user;
if (!req.accessToken) return res.sendStatus(401);
//verify passwords match
if (!req.body.password || !req.body.confirmation ||
req.body.password !== req.body.confirmation) {
return res.sendStatus(400, new Error('Passwords do not match'));

User.findById(req.accessToken.userId, function(err, user) {
if (err) return res.sendStatus(404);
user.hasPassword(req.body.oldPassword, function(err, isMatch) {
if (!isMatch) {
return res.sendStatus(401);
} else {
user.updateAttribute('password', req.body.password, function(err, user) {
if (err) return res.sendStatus(404);
console.log('> password change request processed successfully');
res.status(200).json({msg: 'password change request processed successfully'});

Answer Source

Use built-in User.hashPassword which seen in source code

//Hash the plain password
user.updateAttribute('password', User.hashPassword(req.body.password), function(err, user) {