silenceofworld
silenceofworld

Reputation: 11

Securely Updating User's Password / NodeJs - Mongoose

I am trying to create a secure password reseting system by using JWT. While doing pass reset, i was trying to use mongoose. At first i tried to update my user, only using updateOne() mongoose function. However i have also a password cryption middleware, and in this middleware i couldn't use this.isModified("password"). The system always saying that i didn't modify the password by returning false, although i update document with updateOne() function. Is there anyone help me with that issue. I solve it by using save(). But i want to learn how can i handle with the updateOne()

My Middleware Function:

 /* UserSchema.pre('save', async function (next) {
      if (!this.isModified('password')) {
        return next();
      }
    
      this.password = await bcyrpt.hash(this.password, 12);
      this.passwordConfirm = undefined; // we do not need it anymore so deleting it by = undefined
      next();
    }); */
    
    UserSchema.pre(
      'updateOne',
      { document: true, query: false },
      async function (next) {
        if (!this.isModified('password')) {
          return next(new AppError('ERR PASS DIDNT CHANGE'));
        }
    
        this.password = await bcyrpt.hash(this.password, 12);
        this.passwordConfirm = undefined; // we do not need it anymore so deleting it by = undefined
        next();
      },
    );

My Pass Update Function:

exports.resetPassword = catchAsync(async (req, res, next) => {
  const { token } = req.query;
  const decoded = jwt.verify(token, process.env.JWT_PASS_REFRESH_SECRET);

  const { password, passwordConfirm } = req.body;

  if (!password === passwordConfirm) {
    return next(new AppError('Passwords should be exactly the same'));
  }

  /* let user = await User.findOne({ _id: decoded.id });
  user.password = password;
  user.passwordConfirm = passwordConfirm;
  user = await user.save(); */

  let user = await User.findOne({ _id: decoded.id });
  user = await user.updateOne({ password: password });

  res.status(200).json({
    status: 'succeess',
  });
});

Additional Question: Why some people are just encrypt the pass reset token wihtout JWT and store it in the database? I believe it is not secure, is it? Because, if a hacker looks at our database, it can have info to users' email and tokens. For example he can go to the app and use forgot mail functionality with user's email address and stole the token and use it. Am i missing a point with other encryption systems like crypto. If u have any comments, i will appreciate so much

Upvotes: -1

Views: 21

Answers (0)

Related Questions