Skip to content

Commit

Permalink
Merge pull request #25 from donaldpiret/master
Browse files Browse the repository at this point in the history
Add a no_local option that prevents the use of local hostnames
  • Loading branch information
Vladimir Krylov committed Jan 31, 2015
2 parents e7ab382 + 574cf54 commit e537423
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 1 deletion.
3 changes: 3 additions & 0 deletions README.md
Expand Up @@ -26,6 +26,9 @@ class Pony < ActiveRecord::Base

# with allow_blank
validates :homepage, :url => {:allow_blank => true}

# without local hostnames
validates :homepage, :url => {:no_local => true}
end
```

Expand Down
4 changes: 3 additions & 1 deletion lib/validate_url.rb
Expand Up @@ -11,14 +11,16 @@ class UrlValidator < ActiveModel::EachValidator
def initialize(options)
options.reverse_merge!(:schemes => %w(http https))
options.reverse_merge!(:message => :url)
options.reverse_merge!(:no_local => false)

super(options)
end

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)
unless uri && uri.host && schemes.include?(uri.scheme) && (!options.fetch(:no_local) || uri.host.include?('.'))
record.errors.add(attribute, options.fetch(:message), :value => value)
end
rescue Addressable::URI::InvalidURIError
Expand Down
9 changes: 9 additions & 0 deletions spec/resources/user_with_no_local.rb
@@ -0,0 +1,9 @@
require 'active_model/validations'

class UserWithNoLocal
include ActiveModel::Validations

attr_accessor :homepage

validates :homepage, :url => {:no_local => true}
end
1 change: 1 addition & 0 deletions spec/spec_helper.rb
Expand Up @@ -24,3 +24,4 @@
autoload :UserWithArLegacy, 'resources/user_with_ar_legacy'
autoload :UserWithCustomScheme, 'resources/user_with_custom_scheme'
autoload :UserWithCustomMessage, 'resources/user_with_custom_message'
autoload :UserWithNoLocal, 'resources/user_with_no_local'
21 changes: 21 additions & 0 deletions spec/validate_url_spec.rb
Expand Up @@ -135,6 +135,27 @@
end
end

context "with no_local" do
before do
@user = UserWithNoLocal.new
end

it "should allow a valid internet url" do
@user.homepage = "http://www.example.com"
@user.should be_valid
end

it "should not allow a local hostname" do
@user.homepage = "http://localhost"
@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
end
end

context "with legacy syntax" do
before do
@user = UserWithLegacySyntax.new
Expand Down

0 comments on commit e537423

Please sign in to comment.