generatePasswordResetCode static method
Generate numeric password reset code (OTP-style)
Implementation
static Future<String> generatePasswordResetCode(
String email, {
int length = 6,
}) async {
await Auth.ensureFrameworkTablesExist();
// Check if 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 OTP code
final rng = Random();
final code = List.generate(length, (_) => rng.nextInt(10)).join('');
// Hash OTP before storing
final codeHash = Hashing().hash(code);
// Expire after 15 minutes
final expiresAt =
DateTime.now().add(Duration(minutes: 15)).toIso8601String();
// 🧹 Remove any previous codes for this email
await QueryBuilder(table: 'password_reset_tokens')
.where('email', '=', email)
.delete();
// Store the new code
await QueryBuilder(table: 'password_reset_tokens').insert({
'email': email,
'token': codeHash,
'expires_at': expiresAt,
'created_at': DateTime.now().toIso8601String(),
});
print('📨 Password reset code generated for $email');
return code; // ⚠️ Return plain code to send via email/SMS
}