generate password reset token in node.js
Asked Answered
D

3

12

How do I generate a password reset token in node.js that can be used in a url?

I just need the method for generating the token:

user.reset_password_token = ???;
user.reset_password_expire = expire_date;

Edit -- here's the solution:

user.reset_password_token = require('crypto').randomBytes(32).toString('hex');
Damalis answered 25/9, 2012 at 7:34 Comment(3)
Can you include the rest of the code? : )Blazon
i added the solution I went with.Damalis
Thanks, yeah I ended up using that, i did 48 bytes, I guess it doesnt really matter except for taking up more space, or you think 32 is enough?Blazon
N
23

I'm using this to generate my auth-token:

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

Crypto Node.js v0.8.9 Manual & Documentation

Nguyetni answered 25/9, 2012 at 10:15 Comment(4)
How would I use that w/ the code above? Do I have to move everything into randomBytes callback now?Damalis
user.reset_password_token = require('crypto').randomBytes(32).toString('hex');Damalis
How big does the token need to be realisitically? Does it need to be 32 or can it be 8 for a shorter url.Damalis
@Damalis A reset token is literally a password, so in general anything that is true for storing passwords is true for reset tokens. They aren't as large of a concern as passwords though because tokens should have additional restrictions, such as time limits and limited attempts. In my opinion, you'll be fine with 8 characters if your restrictions are strong enough.Aroid
O
0
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()
Orelia answered 12/2, 2016 at 6:22 Comment(0)
T
0

In this case, first, you should create an instance method on your schema, so, your code must be something like this :

Before you write this function, you must add two fields in your schema.

1. passwordResetExpire
2. passwordResetToken

and the function is:

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;
    };
Tetzel answered 30/8, 2020 at 4:35 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.