discourse/lib/validators/pop3_polling_enabled_setting_validator.rb
Martin Brennan 3d2cace94f
DEV: Add service to validate email settings (#13021)
We have a few places in the code where we need to validate various email related settings, and will have another soon with the improved group email settings UI. This PR introduces a class which can validate POP3, IMAP, and SMTP credentials and also provide a friendly error message for issues if they must be presented to an end user.

This PR does not change any existing code to use the new service. I have added a TODO to change POP3 validation and the email test rake task to use the new validator post-release.
2021-05-13 15:11:23 +10:00

57 lines
1.8 KiB
Ruby

# frozen_string_literal: true
require "net/pop"
class POP3PollingEnabledSettingValidator
def initialize(opts = {})
@opts = opts
end
def valid_value?(val)
# only validate when enabling polling
return true if val == "f"
# ensure we can authenticate
SiteSetting.pop3_polling_host.present? &&
SiteSetting.pop3_polling_username.present? &&
SiteSetting.pop3_polling_password.present? &&
authentication_works?
end
def error_message
if SiteSetting.pop3_polling_host.blank?
I18n.t("site_settings.errors.pop3_polling_host_is_empty")
elsif SiteSetting.pop3_polling_username.blank?
I18n.t("site_settings.errors.pop3_polling_username_is_empty")
elsif SiteSetting.pop3_polling_password.blank?
I18n.t("site_settings.errors.pop3_polling_password_is_empty")
elsif !authentication_works?
I18n.t("site_settings.errors.pop3_polling_authentication_failed")
end
end
private
def authentication_works?
# TODO (martin, post-2.7 release) Change to use EmailSettingsValidator
# EmailSettingsValidator.validate_pop3(
# host: SiteSetting.pop3_polling_host,
# port: SiteSetting.pop3_polling_port,
# ssl: SiteSetting.pop3_polling_ssl,
# username: SiteSetting.pop3_polling_username,
# password: SiteSetting.pop3_polling_password,
# openssl_verify: SiteSetting.pop3_polling_openssl_verify
# )
@authentication_works ||= begin
pop3 = Net::POP3.new(SiteSetting.pop3_polling_host, SiteSetting.pop3_polling_port)
pop3.enable_ssl(OpenSSL::SSL::VERIFY_NONE) if SiteSetting.pop3_polling_ssl
pop3.auth_only(SiteSetting.pop3_polling_username, SiteSetting.pop3_polling_password)
rescue Net::POPAuthenticationError
false
else
true
end
end
end