discourse/lib/user_name_suggester.rb

56 lines
1.6 KiB
Ruby
Raw Normal View History

module UserNameSuggester
2016-01-27 16:04:11 +08:00
GENERIC_NAMES = ['i', 'me', 'info', 'support', 'admin', 'webmaster', 'hello', 'mail', 'office', 'contact', 'team']
2015-03-27 07:10:53 +08:00
def self.suggest(name, allow_username = nil)
return unless name.present?
name = parse_name_from_email(name)
2015-03-27 07:10:53 +08:00
find_available_username_based_on(name, allow_username)
end
def self.parse_name_from_email(name)
if name =~ User::EMAIL
# When 'walter@white.com' take 'walter'
name = Regexp.last_match[1]
# When 'me@eviltrout.com' take 'eviltrout'
2016-01-27 16:04:11 +08:00
name = Regexp.last_match[2] if GENERIC_NAMES.include?(name)
end
name
end
2015-03-27 07:10:53 +08:00
def self.find_available_username_based_on(name, allow_username = nil)
name = fix_username(name)
i = 1
attempt = name
2015-03-27 07:10:53 +08:00
until attempt == allow_username || User.username_available?(attempt)
suffix = i.to_s
max_length = User.username_length.end - suffix.length - 1
attempt = "#{name[0..max_length]}#{suffix}"
i += 1
end
attempt
end
def self.fix_username(name)
rightsize_username(sanitize_username(name))
end
def self.sanitize_username(name)
name = ActiveSupport::Inflector.transliterate(name)
# 1. replace characters that aren't allowed with '_'
name.gsub!(UsernameValidator::CONFUSING_EXTENSIONS, "_")
name.gsub!(/[^\w.-]/, "_")
# 2. removes unallowed leading characters
name.gsub!(/^\W+/, "")
# 3. removes unallowed trailing characters
name.gsub!(/[^A-Za-z0-9]+$/, "")
# 4. unify special characters
name.gsub!(/[-_.]{2,}/, "_")
name
end
def self.rightsize_username(name)
name.ljust(User.username_length.begin, '1')[0, User.username_length.end]
end
2014-03-19 06:02:33 +08:00
end