2factor-auth
![NPM](https://nodei.co/npm/2factor-auth.png?compact=true)
Module for generating and verifying 2FA codes (specifically TOTP and HOTP).
Also contains utilities for handling common 2FA business logic, such as generating backup codes and otpauth urls.
Install
npm install --save 2factor-auth
Usage
with async/await (or promises)
const tfa = require('2factor-auth');
function registerUserTwoFactor() {
const serviceName = 'Cool service that is 2FA protected';
const account = 'myUsername@email.com';
const key = await tfa.generateKeyPromise(32);
const codes = await tfa.generateBackupCodesPromise(8);
const url = tfa.generateURL(serviceName, account, key);
}
function verifyTwoFactorCode(secret_key, receivedCode) {
const valid = tfa.verifyTOTP(secret_key, receivedCode);
const validWithDrift = tfa.verifyTOTP(secret_key, receivedCode, {
beforeDrift: 2,
afterDrift: 2
});
return valid;
}
with Callbacks
const tfa = require('2factor-auth');
function registerUserTwoFactor(callback) {
const serviceName = 'Cool service that is 2FA protected';
const account = 'myUsername@email.com';
tfa.generateKey(32, (err, key) => {
if (err) {
callback(err);
return;
}
tfa.generateBackupCodes(8, (err, codes) => {
if (err) {
callback(err);
return;
}
const url = tfa.generateURL(serviceName, account, key);
callback(null);
});
});
}
function verifyTwoFactorCode(secret_key, receivedCode) {
const valid = tfa.verifyTOTP(secret_key, receivedCode);
const validWithDrift = tfa.verifyTOTP(secret_key, receivedCode, {
beforeDrift: 2,
afterDrift: 2
});
return valid;
}