-
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathurl_validator.rb
More file actions
70 lines (54 loc) · 1.76 KB
/
url_validator.rb
File metadata and controls
70 lines (54 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# frozen_string_literal: true
require 'html2rss/url'
module Html2rss
module Web
##
# URL validation and pattern matching utilities built on Html2rss::Url
module UrlValidator
MAX_URL_LENGTH = 2048
class << self
# @param url [String]
# @return [String, nil]
def canonical_url(url)
normalize_url(url)
end
# @param url [String]
# @return [Boolean]
def valid_url?(url)
!canonical_url(url).nil?
end
# @param account [Hash]
# @param url [String]
# @return [Boolean]
def url_allowed?(account, url)
return false unless account && url
allowed_urls = Array(account[:allowed_urls])
return false unless (normalized_url = canonical_url(url))
return false if allowed_urls.empty?
allowed_urls.any? do |pattern|
wildcard?(pattern) ? match_wildcard?(pattern, normalized_url) : match_exact?(pattern, normalized_url)
end
end
private
def match_exact?(pattern, normalized_url)
return true if pattern == normalized_url
normalized_pattern = canonical_url(pattern)
normalized_pattern ? normalized_pattern == normalized_url : false
end
def match_wildcard?(pattern, normalized_url)
return true if pattern == '*'
File.fnmatch?(pattern, normalized_url, File::FNM_CASEFOLD)
end
def wildcard?(pattern)
pattern.include?('*')
end
def normalize_url(url)
return nil unless url.is_a?(String) && !url.empty? && url.length <= MAX_URL_LENGTH
Html2rss::Url.for_channel(url).to_s
rescue StandardError
nil
end
end
end
end
end