discourse/lib/validators/url_validator.rb
Martin Brennan edbc356593
FIX: Replace deprecated URI.encode, URI.escape, URI.unescape and URI.unencode (#8528)
The following methods have long been deprecated in ruby due to flaws in their implementation per http://blade.nagaokaut.ac.jp/cgi-bin/vframe.rb/ruby/ruby-core/29293?29179-31097:

URI.escape
URI.unescape
URI.encode
URI.unencode
escape/encode are just aliases for one another. This PR uses the Addressable gem to replace these methods with its own encode, unencode, and encode_component methods where appropriate.

I have put all references to Addressable::URI here into the UrlHelper to keep them corralled in one place to make changes to this implementation easier.

Addressable is now also an explicit gem dependency.
2019-12-12 12:49:21 +10:00

25 lines
611 B
Ruby

# frozen_string_literal: true
class UrlValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
if value.present?
valid =
begin
uri = URI.parse(value)
uri.is_a?(URI::HTTP) && !uri.host.nil? && uri.host.include?(".")
rescue URI::Error => e
if (e.message =~ /URI must be ascii only/)
value = UrlHelper.encode(value)
retry
end
nil
end
unless valid
record.errors.add(attribute, options[:message] || I18n.t('errors.messages.invalid'))
end
end
end
end