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


如何在

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

加密节点.js v0.8.9 手册和文档

function customToken() {
    var buffreValue = new Buffer(64);
    for (var i = 0; i < buffreValue.length; i++) {
        buffreValue[i] = Math.floor(Math.random() * 256);
    }
    var token = buffreValue.toString('base64');
    return token;
}
var getToken = customToken()

在这种情况下,首先,您应该在架构上创建一个实例方法,因此,您的代码必须如下所示:

在编写此函数之前,必须在架构中添加两个字段。

1. 密码重置过期
2. 密码重置令牌

函数为:

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

最新更新