2013-07-24 39 views

回答

19

查看源也被添加到所谓setPassword架构的功能。 我相信在验证后,您可以调用它来更改用户的密码。

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); 
     }); 
    }); 
}; 
+1

刚试过这个,它的工作原理!这应该被标记为接受的答案。 –

+1

反正老线程:实际上,你不需要认证。从帐户中检索用户,设置密码,然后在回调中输入user.save,就完成了。 –

+0

验证在一个'忘记密码的电子邮件或确保用户的一些其他方式的感觉是,他们声称 – user1441287

6

很好的回答,但对于那些谁来自MEAN堆栈(采用护照的地方,没有护照,本地猫鼬):

//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; 
}); 

因此,这将改变通:

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

无需验证。检索从使用findByUsername()方法,其通过护照和本地猫鼬放置在模型帐户的用户,然后运行setPassword(),然后user.save()在回调。

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); 
}) 

我拨打的用户sanitizedUser(),因为我已经配置护照本地猫鼬有来无回用findByUsername()密码或盐田和模型护照选项。