Passport-Local Mongoose - Change password? Passport-Local Mongoose - Change password? mongoose mongoose

Passport-Local Mongoose - Change password?


Looking at the source there is a function that is added to the schema called setPassword.I believe that after authenticating you can call it to change the password for the user.

schema.methods.setPassword = function (password, cb) {    if (!password) {        return cb(new BadRequestError(options.missingPasswordError));    }    var self = this;    crypto.randomBytes(options.saltlen, function(err, buf) {        if (err) {            return cb(err);        }        var salt = buf.toString('hex');        crypto.pbkdf2(password, salt, options.iterations, options.keylen, function(err, hashRaw) {            if (err) {                return cb(err);            }            self.set(options.hashField, new Buffer(hashRaw, 'binary').toString('hex'));            self.set(options.saltField, salt);            cb(null, self);        });    });};


No need to authenticate. Retrieve user from account using findByUsername() method, which was placed on the model by passport-local-mongoose, then run setPassword(), then user.save() in the callback.

userModel.findByUsername(email).then(function(sanitizedUser){    if (sanitizedUser){        sanitizedUser.setPassword(newPasswordString, function(){            sanitizedUser.save();            res.status(200).json({message: 'password reset successful'});        });    } else {        res.status(500).json({message: 'This user does not exist'});    }},function(err){    console.error(err);})

I call the user sanitizedUser() because I have configured passport-local-mongoose to not return the password or salt fields using findByUsername() and the passport options in the model.


Good answer, but for ones who come from the MEAN stack (uses passport-local, not passport-local-mongoose):

//in app/models/user.js/** * Virtuals */UserSchema.virtual('password').set(function(password) {    this._password = password;    this.salt = this.makeSalt();    this.hashed_password = this.encryptPassword(password);}).get(function() {    return this._password;});

So this would change the pass:

user.password = '12345678';//and after this setter...user.save(function(err){ //...save    if(err)...});