Skip to content

Time-Based One-Time Passwords — TOTP Implementation for 2FA

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you'll learn about Totp Implementation. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

TOTP is a widely adopted second factor using time-based codes generated by authenticator apps like Google Authenticator or Authy.

const speakeasy = require('speakeasy');
const qrcode = require('qrcode');

// Generate TOTP secret
function setupTOTP(userEmail) {
  const secret = speakeasy.generateSecret({
    name: `ScanApp:${userEmail}`,
    issuer: 'ScanApp',
    length: 20
  });

  return {
    secret: secret.base32,
    otpauth_url: secret.otpauth_url
  };
}

// Generate QR code for provisioning
async function provisionTOTP(userEmail) {
  const { secret, otpauth_url } = setupTOTP(userEmail);
  const qrCode = await qrcode.toDataURL(otpauth_url);

  // Store secret temporarily for verification
  await redis.setex(`totp_pending:${userEmail}`, 300, secret);

  return { qrCode, secret };
}

// Verify TOTP code
function verifyTOTP(secret, token) {
  return speakeasy.totp.verify({
    secret: secret,
    encoding: 'base32',
    token: token,
    window: 1, // Allow 1 step before/after for clock drift
    step: 30   // 30 second window
  });
}

// Generate backup codes
function generateBackupCodes(count = 10) {
  const codes = [];
  for (let i = 0; i < count; i++) {
    const code = crypto.randomBytes(4).toString('hex').toUpperCase();
    const hash = crypto.createHash('sha256').update(code).digest('hex');
    codes.push({ code: `SCAN-${code}`, hash });
  }
  return codes;
}

TOTP provides strong second-factor authentication without requiring network connectivity for Code Generation.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro