diff --git a/lib/validate_url.rb b/lib/validate_url.rb index 663fed6..0a319b8 100644 --- a/lib/validate_url.rb +++ b/lib/validate_url.rb @@ -22,13 +22,21 @@ def validate_each(record, attribute, value) schemes = [*options.fetch(:schemes)].map(&:to_s) begin uri = Addressable::URI.parse(value) - unless uri && uri.host && schemes.include?(uri.scheme) && (!options.fetch(:no_local) || uri.host.include?('.')) + unless uri && uri.host && schemes.include?(uri.scheme) && (!options.fetch(:no_local) || not_localhost?(uri.host)) record.errors.add(attribute, options.fetch(:message), :value => value) end rescue Addressable::URI::InvalidURIError record.errors.add(attribute, options.fetch(:message), :value => value) end end + + private + + def not_localhost?(host) + return false if host == '127.0.0.1' + + host.include?('.') + end end module ClassMethods diff --git a/spec/validate_url_spec.rb b/spec/validate_url_spec.rb index 20c47de..441f2b3 100644 --- a/spec/validate_url_spec.rb +++ b/spec/validate_url_spec.rb @@ -158,6 +158,11 @@ @user.should_not be_valid end + it "should not allow a local ip" do + @user.homepage = "http://127.0.0.1" + @user.should_not be_valid + end + it "should not allow weird urls that get interpreted as local hostnames" do @user.homepage = "http://http://example.com" @user.should_not be_valid