existing_username_validator.rb 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. # frozen_string_literal: true
  2. class ExistingUsernameValidator < ActiveModel::EachValidator
  3. def validate_each(record, attribute, value)
  4. @value = value
  5. return if @value.blank?
  6. if options[:multiple]
  7. record.errors.add(attribute, not_found_multiple_message) if usernames_with_no_accounts.any?
  8. elsif usernames_with_no_accounts.any? || usernames_and_domains.size > 1
  9. record.errors.add(attribute, not_found_message)
  10. end
  11. end
  12. private
  13. def usernames_and_domains
  14. @value.split(',').filter_map do |string|
  15. username, domain = string.strip.gsub(/\A@/, '').split('@', 2)
  16. domain = nil if TagManager.instance.local_domain?(domain)
  17. next if username.blank?
  18. [string, username, domain]
  19. end
  20. end
  21. def usernames_with_no_accounts
  22. usernames_and_domains.filter_map do |(string, username, domain)|
  23. string unless Account.find_remote(username, domain)
  24. end
  25. end
  26. def not_found_multiple_message
  27. I18n.t('existing_username_validator.not_found_multiple', usernames: usernames_with_no_accounts.join(', '))
  28. end
  29. def not_found_message
  30. I18n.t('existing_username_validator.not_found')
  31. end
  32. end