Jabaa
Jabaa

Reputation: 1753

One time password generation in express js

I am trying to generate OTP in express js using speakeasy https://www.npmjs.com/package/speakeasy.

Here is the sample code i've tried

var speakeasy = require('speakeasy');
        var secret = speakeasy.generateSecret({length:32});

        //generate token
        var code = speakeasy.totp({
            secret:secret.base32,
            encoding: 'base32',
            step:300,
            window:100,
            counter:123
        });

        //verify token
        var verified = speakeasy.totp.verify({
            secret:secret.base32 ,
            encoding: 'base32',
            token: code
        });

When verify the token console.log(verified) always return false.

I've followed this github link https://github.com/speakeasyjs/speakeasy/issues/52 but it didn't help

Upvotes: 0

Views: 6677

Answers (5)

Shah Fahad
Shah Fahad

Reputation: 207

A very simple way to generate 1 time otp is to utilize Math random function. Here is how to do it for 4 unique digit otp by making a utility function in your express project etc.

// generateOtp.js

/**
 * Math.random() returns a number beterrn 0 and 1. 
 * It is then added with 1000 and multiplied with 9000 to return a float,
 * Which is then round up to greatest integer less than or equal to its numeric argument.
 * 
 * @returns 4 unique digits
 */
const generateOtp = () => Math.floor(1000 + Math.random() * 9000)

// Export
module.exports = generateOtp;

Now, use this function where required.

Example: Here is how to utilize function.

// anyfile.js
const generateOtp = require(" /*Path to your utility function*/ ");

// Get otp
const otp = generateOtp();

console.log(otp); // 4 unique digits

// Do the reset i.e, Send it to user via nodemailer etc...

More on Math random

Upvotes: 0

Ankit
Ankit

Reputation: 671

module.exports = (num = 4) => {
    return Math.random().toFixed(num).substr(`-${num}`)
}

Edit:.substr is deprecated

`.substr` is now [deprecated][1]. We can use this approach instead:
module.exports = (num = 4) => {
     Math.random().toFixed(num).substring(0, length);
}

OTP: 9749

Upvotes: 3

Jame's Nguyen
Jame's Nguyen

Reputation: 11

You should be added counter = 123 into verify function:

var verified = speakeasy.totp.verify({
      secret: secret.base32,
      encoding: 'base32',
      token: code, 
      counter: 123
});

Upvotes: 1

user2886291
user2886291

Reputation: 11

Add step value given while generating token for verify.

var verified = speakeasy.totp.verify({
        secret:secret.base32 ,
        encoding: 'base32',
        token: code,
        step: 300
    });

Upvotes: 1

David Cho-Lerat
David Cho-Lerat

Reputation: 21

I don't know about speakeasy, but we've successfully used notp in our project to generate one-time passwords we use with Express, maybe this might help : https://www.npmjs.com/package/notp

Upvotes: 2

Related Questions