From 5187e888aefd23255e4eec996b9ea44c24f64ee8 Mon Sep 17 00:00:00 2001 From: Victor Costa Date: Fri, 23 May 2014 13:41:35 -0300 Subject: [PATCH] Avoid infinite loop on username suggestion --- app/helpers/account_helper.rb | 9 +++++++-- test/unit/account_helper_test.rb | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/app/helpers/account_helper.rb b/app/helpers/account_helper.rb index 09ed494..9a6c13d 100644 --- a/app/helpers/account_helper.rb +++ b/app/helpers/account_helper.rb @@ -15,12 +15,17 @@ module AccountHelper def suggestion_based_on_username(requested_username='') return "" if requested_username.empty? + + requested_username = requested_username.downcase.tr("^#{Profile::IDENTIFIER_FORMAT}", '') usernames = [] + tries = 0 3.times do begin valid_name = requested_username + rand(1000).to_s - end while (usernames.include?(valid_name) || !Person.is_available?(valid_name, environment)) - usernames << valid_name + tries += 1 + invalid = usernames.include?(valid_name) || !Person.is_available?(valid_name, environment) + end while tries <= 10 && invalid + usernames << valid_name unless invalid end usernames end diff --git a/test/unit/account_helper_test.rb b/test/unit/account_helper_test.rb index 69656aa..4f39e83 100644 --- a/test/unit/account_helper_test.rb +++ b/test/unit/account_helper_test.rb @@ -18,4 +18,19 @@ class AccountHelperTest < ActiveSupport::TestCase end end + should 'remove chars which are not allowed' do + stubs(:environment).returns(Environment.default) + suggestions = suggestion_based_on_username('z/%&#e') + suggestions.each do |suggestion| + assert_no_match /.*%&#.*/, suggestion + end + end + + should 'return empty suggestions if do not find any identifier available' do + stubs(:environment).returns(Environment.default) + Person.stubs(:is_available?).returns(false) + suggestions = suggestion_based_on_username('z/%&#e') + assert_equal [], suggestions + end + end -- libgit2 0.21.2