Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 hash instead it just saves a plain text in the db. I am using loopback-component-passport 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
app.post('/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'});
        });
      }
    });
  });
});
like image 611
Vicky Gonsalves Avatar asked Feb 17 '16 05:02

Vicky Gonsalves


People also ask

How do I reset my LoopBack password?

Resetting a user's password. Use the User. resetPassword() method to reset a user's password.

What is loopback4?

LoopBack is a Node. js API framework that enables you to create APIs quickly that interact with backend resources like databases and services. LoopBack 4, the next generation of LoopBack, includes: A brand new core rewritten in TypeScript that makes this framework simpler to use and easier to extend than ever.


1 Answers

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) {
    ...
});
like image 124
Medet Tleukabiluly Avatar answered Sep 18 '22 15:09

Medet Tleukabiluly