authenticator.test.js 1.45 KB
/**
 * Created by lintry on 2017/5/19.
 */

const Authenticator = require('../lib/authenticator');
const chalk = require('chalk');
const fs = require('fs-extra');
const path = require('path');

let secret = 'vH6OdbUEjSukTqlDvW3TYdusjiOIkxRnAHNTjJewfZa5yNueG9wx1N9pJMFOmPAV';
let authenticator = new Authenticator(secret, {algorithm: 'sha512'});
console.log(chalk.cyan('totp的secret'));
console.log(secret, authenticator.totp_options);

let token = process.argv[2];
if (!token) {
  token = authenticator.totp();
  console.error(chalk.red('none token found, we generate a new token instead'), token);
  return;
}
console.log(chalk.green('token is'), token);

let verify = authenticator.verify(token);
console.log(chalk.magenta('verify is '), (verify ? chalk.green : chalk.red)(verify));
console.log(chalk.blue('verifyDelta is '), authenticator.verifyDelta(token));


let img_path = path.resolve(process.cwd(), 'img');
let qr = path.resolve(img_path, 'qr.svg');

fs.ensureDir(img_path, function (err, added_root) {
  if (err) {
    return console.error(chalk.red('create folder error'), chalk.red(JSON.stringify(err, null, 4)));
  }
  added_root && console.log(chalk.green(img_path + ' is created'));

  let fd = fs.openSync(qr, 'w');
  fs.writeSync(fd, authenticator.getQR('totp@gitlab.kmlab.com', '通行密钥'));
  fs.closeSync(fd);

  console.log(chalk.yellow(authenticator.getOtpAuth('totp@gitlab.kmlab.com', '通行密钥')))
});

console.log('QR SVG output is', img_path, qr);