resetPasswordWithCode static method

Future<bool> resetPasswordWithCode({
  1. required String email,
  2. required String code,
  3. required String newPassword,
})

Verify reset code and change password

Implementation

static Future<bool> resetPasswordWithCode({
  required String email,
  required String code,
  required String newPassword,
}) async {
  await Auth.ensureFrameworkTablesExist();

  if (newPassword.length < Auth.config.passwordMinLength) {
    throw AuthException(
        message:
            'Password must be at least ${Auth.config.passwordMinLength} characters.');
  }

  // Look for valid code
  final record = await QueryBuilder(table: 'password_reset_tokens')
      .where('email', '=', email)
      .where('expires_at', '>', DateTime.now().toIso8601String())
      .first();

  if (record == null) {
    Log.debug('โŒ Invalid or expired password reset code for $email');
    throw AuthException(message: 'Invalid or expired reset code.');
  }
  final isValid = Hashing().verify(code, record['token']);

  if (!isValid) {
    Log.warning('โŒ Invalid verification code for $email');
    return false;
  }
  // Hash new password
  final newHashedPassword = Hashing().hash(newPassword);

  // Update user password
  await QueryBuilder(table: Auth.config.table)
      .where(Auth.config.emailColumn, '=', email)
      .update({
    Auth.config.passwordColumn: newHashedPassword,
    'updated_at': DateTime.now().toIso8601String(),
  });

  // ๐Ÿงน Remove used reset token
  await QueryBuilder(table: 'password_reset_tokens')
      .where('email', '=', email)
      .delete();

  Log.debug('โœ… Password successfully reset for $email');
  return true;
}