2

Here I am trying to verify mobile number in user module. I have created token and I sent to user but whenever user is trying to verify using that particular token 'Password' and 'salt' automatically got changed. How to avoid this? Some one help me out .. here I want to update only

user.Mobileverification = 'verfied';
user.Mobileverificationcode = undefined;
user.mobileVerificationExpires = undefined;

Above three variables got changed but I don't know why password and salt has changed?

I have given my routes below:

app.route('/auth/mobilereset/:token').get(users.mobileresetResetToken);
app.route('/auth/mobilereset/:token').post(users.mobilereset);

controller:

exports.mobileresetResetToken = function(req, res) {
    User.findOne({
        Mobileverificationcode :req.params.token,
        mobileVerificationExpires: {
            $gt: Date.now()
         }
        // resetPasswordToken: req.params.token,
        // resetPasswordExpires: {
            // $gt: Date.now()
        // }
    }, function(err, user) {
        if (!user) {
            res.send({
                message: 'Invalid token'
            });


        } else {

            console.log('working fine');
        }
    });
};



exports.mobilereset = function(req, res, next) {


    async.waterfall([

        function(done) {
            User.findOne({
                Mobileverificationcode: req.params.token,
                mobileVerificationExpires: {
                    $gt: Date.now()
                }
            }, function(err, user) {
                if (!err && user) {

                        user.Mobileverification = 'verfied';
                        user.Mobileverificationcode = undefined;
                        user.mobileVerificationExpires = undefined;

                        user.save(function(err) {
                            if (err) {
                                return res.status(400).send({
                                    message: errorHandler.getErrorMessage(err)
                                });
                            } else {
                                req.login(user, function(err) {
                                    if (err) {
                                        res.status(400).send(err);
                                    } else {
                                        // Return authenticated user 
                                        res.json(user);

                                        done(err, user);
                                    }
                                });
                            }
                        });

                } else {
                    return res.status(400).send({
                        message: 'reset token is invalid or has expired.'
                    });
                }
            });
        },

    ], function(err) {
        if (err) return next(err);
    });
};

model:

var UserSchema = new Schema({

    username: {
        type: String,
        unique: 'testing error message',
        required: 'Please fill in a username',
        trim: true
    },
    password: {
        type: String,
        default: '',
        // validate: [validateLocalStrategyPassword, 'Password should be longer']
    },
    email: {
        type: String,
        trim: true,
        default: '',
        // validate: [validateLocalStrategyProperty, 'Please fill in your email'],
        // match: [/.+\@.+\..+/, 'Please fill a valid email address']
    },
    Mobilenumber: {
        type: String,
        default: ''
    },


    roles: {
        type: [{
            type: String,
            enum: ['user', 'admin']
        }],
        default: ['user']
    },
    salt: {
        type: String
    },
    provider: {
        type: String,
        required: 'Provider is required'
    },
    providerData: {},
    additionalProvidersData: {},

    updated: {
        type: Date
    },
    created: {
        type: Date,
        default: Date.now
    },
    /* For reset password */
    Mobileverificationcode: {
        type: String,
    },
    mobileVerificationExpires: {
        type: Date
    },
    Mobileverification: {
        type: String,
        trim: true,
        default: 'Not Verified',
    },
    resetPasswordToken: {
        type: String
    },
    resetPasswordExpires: {
        type: Date
    }
});
mmvsbg
  • 3,570
  • 17
  • 52
  • 73

1 Answers1

0

I don't know if you removed this or not but in MEAN.js user model, you have to be careful with the following code block:

/**
 * Hook a pre save method to hash the password
 */
UserSchema.pre('save', function (next) {
   if (this.password && this.isModified('password')) {
     this.salt = crypto.randomBytes(16).toString('base64');
    this.password = this.hashPassword(this.password);
   }

  next();
});

Which will be called right before you save the user data. That's probably why password and salt keep changing... You are calling user.save in mobile.reset() and that code block above is still present somewhere.

Update: A possible way of doing it is:

/**
 * Hook a pre save method to hash the password
 */
UserSchema.pre('save', function (next) {
   if(!this.isModified('Mobileverification') && !this.isModified('Mobileverificationcode') && !this.isModified('mobileVerificationExpires')) {
       if (this.password && this.isModified('password')) {
         this.salt = crypto.randomBytes(16).toString('base64');
         this.password = this.hashPassword(this.password);
       }
    }

  next();
});

However it might need a few adjustments, such as improving this pre-save hook according to your needs and testing password changing and mobile verification to see if nothing is broken.

pgrodrigues
  • 2,083
  • 1
  • 24
  • 28
  • without changing salt and password how can i change only Mobileverificationcode ,mobileVerificationExpires, Mobileverification –  Jul 18 '16 at 11:08