在node.js中生成密码重置令牌

在node.js中生成密码重置令牌,node.js,forgot-password,Node.js,Forgot Password,如何在node.js中生成可在url中使用的密码重置令牌 我只需要生成令牌的方法: user.reset_password_token = ???; user.reset_password_expire = expire_date; 编辑--以下是解决方案: user.reset_password_token = require('crypto').randomBytes(32).toString('hex'); 我正在使用它生成我的身份验证令牌: require('crypto').ran

如何在node.js中生成可在url中使用的密码重置令牌

我只需要生成令牌的方法:

user.reset_password_token = ???;
user.reset_password_expire = expire_date;
编辑--以下是解决方案:

user.reset_password_token = require('crypto').randomBytes(32).toString('hex');

我正在使用它生成我的身份验证令牌:

require('crypto').randomBytes(32, function(ex, buf) {
    var token = buf.toString('hex');
});

函数customToken(){
var buffreValue=新缓冲区(64);
对于(变量i=0;i
在这种情况下,首先,您应该在模式上创建一个实例方法,因此,您的代码必须如下所示:

在编写此函数之前,必须在模式中添加两个字段

1。密码重置过期
2。passwordResetToken

且函数为:

userSchema.methods.createPasswordResetToken = function () {
      const resetToken = crypto.randomBytes(32).toString('hex');
      this.passwordResetToken = crypto.createHash('sha256').update(resetToken).digest('hex');
      // Please note that you need to specify a time to expire this token. In this example is (10 min)
      this.passwordResetExpire = Date.now() + 10 * 60 * 1000;
      return resetToken;
    };

我将如何使用上述代码?我必须现在将所有内容移动到randomBytes回调中吗?
user.reset\u password\u token=require('crypto')。randomBytes(32)。toString('hex')令牌实际需要多大?对于较短的url,它需要是32还是8。@chovy重置令牌实际上就是密码,所以一般来说,任何对存储密码正确的东西对重置令牌都是正确的。它们不像密码那么重要,因为令牌应该有额外的限制,比如时间限制和有限的尝试。在我看来,如果您的限制足够强,您可以使用8个字符。您可以包含代码的其余部分吗?:)我添加了我使用的解决方案。谢谢,是的,我最终使用了48个字节,我想除了占用更多空间之外,这并不重要,或者你认为32个就足够了?
userSchema.methods.createPasswordResetToken = function () {
      const resetToken = crypto.randomBytes(32).toString('hex');
      this.passwordResetToken = crypto.createHash('sha256').update(resetToken).digest('hex');
      // Please note that you need to specify a time to expire this token. In this example is (10 min)
      this.passwordResetExpire = Date.now() + 10 * 60 * 1000;
      return resetToken;
    };