generateNumericVerificationCode static method

Future<String> generateNumericVerificationCode(
  1. String email, {
  2. int length = 6,
})

Generate numeric verification code (like OTP)

Implementation

static Future<String> generateNumericVerificationCode(
  String email, {
  int length = 6,
}) async {
  await Auth.ensureFrameworkTablesExist();

  // Check if the user exists
  final user = await QueryBuilder(table: Auth.config.table)
      .where(Auth.config.emailColumn, '=', email)
      .first();
  if (user == null) {
    throw AuthException('No account found for this email.');
  }

  // Generate numeric code
  final rng = Random();
  final code = List.generate(length, (_) => rng.nextInt(10)).join('');

  // Hash code before storing
  final codeHash = Hashing().hash(code);

  // Expire after 10 minutes
  final expiresAt =
      DateTime.now().add(Duration(minutes: 10)).toIso8601String();

  // 🧹 Delete any previous unused codes for this email
  await QueryBuilder(table: 'email_verification_tokens')
      .where('email', '=', email)
      .delete();

  // Store new verification code
  await QueryBuilder(table: 'email_verification_tokens').insert({
    'email': email,
    'token': codeHash,
    'expires_at': expiresAt,
    'created_at': DateTime.now().toIso8601String(),
  });

  print('📨 Verification code generated for $email');

  return code; // ⚠️ Return plain code to send via mail or SMS
}