簡體   English   中英

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

[英]generate password reset token in 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');
});

Crypto Node.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.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;
    };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM