2016-06-20 05:34:34 -04:00
|
|
|
# AddressableUrlValidator
|
2016-06-17 09:09:39 -04:00
|
|
|
#
|
2016-06-24 05:35:32 -04:00
|
|
|
# Custom validator for URLs. This is a stricter version of UrlValidator - it also checks
|
|
|
|
# for using the right protocol, but it actually parses the URL checking for any syntax errors.
|
|
|
|
# The regex is also different from `URI` as we use `Addressable::URI` here.
|
2016-06-17 09:09:39 -04:00
|
|
|
#
|
2016-06-20 05:34:34 -04:00
|
|
|
# By default, only URLs for http, https, ssh, and git protocols will be considered valid.
|
2016-06-17 09:09:39 -04:00
|
|
|
# Provide a `:protocols` option to configure accepted protocols.
|
|
|
|
#
|
|
|
|
# Example:
|
|
|
|
#
|
|
|
|
# class User < ActiveRecord::Base
|
2016-06-20 05:34:34 -04:00
|
|
|
# validates :personal_url, addressable_url: true
|
2016-06-17 09:09:39 -04:00
|
|
|
#
|
2016-06-20 05:34:34 -04:00
|
|
|
# validates :ftp_url, addressable_url: { protocols: %w(ftp) }
|
2016-06-17 09:09:39 -04:00
|
|
|
#
|
2016-06-20 05:34:34 -04:00
|
|
|
# validates :git_url, addressable_url: { protocols: %w(http https ssh git) }
|
2016-06-17 09:09:39 -04:00
|
|
|
# end
|
|
|
|
#
|
|
|
|
class AddressableUrlValidator < ActiveModel::EachValidator
|
2016-06-30 07:17:37 -04:00
|
|
|
DEFAULT_OPTIONS = { protocols: %w(http https ssh git) }
|
|
|
|
|
2016-06-17 09:09:39 -04:00
|
|
|
def validate_each(record, attribute, value)
|
|
|
|
unless valid_url?(value)
|
|
|
|
record.errors.add(attribute, "must be a valid URL")
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2016-06-20 11:20:53 -04:00
|
|
|
private
|
|
|
|
|
2016-06-17 09:09:39 -04:00
|
|
|
def valid_url?(value)
|
|
|
|
return false unless value
|
|
|
|
|
2016-06-23 11:18:02 -04:00
|
|
|
valid_protocol?(value) && valid_uri?(value)
|
2016-06-17 09:09:39 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def valid_uri?(value)
|
2016-07-01 03:02:45 -04:00
|
|
|
Gitlab::UrlSanitizer.valid?(value)
|
2016-06-17 09:09:39 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def valid_protocol?(value)
|
2016-06-30 07:17:37 -04:00
|
|
|
options = DEFAULT_OPTIONS.merge(self.options)
|
|
|
|
value =~ /\A#{URI.regexp(options[:protocols])}\z/
|
2016-06-17 09:09:39 -04:00
|
|
|
end
|
|
|
|
end
|