Skip to content

Commit e3d6e1c

Browse files
authored
Merge pull request #312 from Trim/fix-bookmark-link-validation
bookmark defaults scheme to HTTP and HTTP validator only check scheme and host
2 parents 73622bb + f74c2bc commit e3d6e1c

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

app/models/bookmark.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,21 @@ class Bookmark < Content
2929
http_url: { message: "Le lien n'est pas valide" },
3030
length: { maximum: 255, message: "Le lien est trop long" }
3131

32+
def link=(raw)
33+
raw.strip!
34+
return write_attribute :url, nil if raw.blank?
35+
uri = URI.parse(raw)
36+
# Default to HTTP link if neither scheme nor host is found
37+
if uri.scheme.blank? && uri.host.blank?
38+
raw = "http://#{raw}"
39+
uri = URI.parse(raw)
40+
end
41+
write_attribute :link, uri.to_s
42+
# Let raw value if error when parsed, HttpUrlValidator will manage it
43+
rescue URI::InvalidURIError
44+
write_attribute :link, raw
45+
end
46+
3247
def create_node(attrs={})
3348
attrs[:cc_licensed] = false
3449
super

app/validators/http_url_validator.rb

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,16 @@ def validate_each(record, attribute, value)
99
private
1010

1111
def valid?(value, options)
12+
# Valid links can be parsed by URI
1213
uri = URI.parse(value)
13-
if uri.scheme.blank? && uri.host.blank?
14-
value = "http://#{value}"
15-
uri = URI.parse(value)
16-
end
14+
# Authorize protocol
1715
if options.has_key?(:protocols)
18-
return true if options[:protocols].include?(uri.scheme)
16+
return options[:protocols].include?(uri.scheme)
1917
end
20-
uri.scheme.nil? && uri.host == MY_DOMAIN
18+
# Links starting with "//MY_DOMAIN" are current scheme dependent and are valid
19+
return true if uri.scheme.nil? && uri.host == MY_DOMAIN
20+
# All other links are valid only if scheme and host exists
21+
return uri.scheme.present? && uri.host.present?
2122
rescue URI::InvalidURIError
2223
false
2324
end

0 commit comments

Comments
 (0)