From fa72db0c9aee7e1725be43894736d3a29a2ff882 Mon Sep 17 00:00:00 2001 From: dmxhZGp1c2hh Date: Mon, 22 Feb 2016 06:40:41 +0200 Subject: [PATCH] add local ip test --- lib/validate_url.rb | 10 +++++++++- spec/validate_url_spec.rb | 5 +++++ 2 files changed, 14 insertions(+), 1 deletion(-) 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