Module: RedirectSafely

Extended by:
RedirectSafely
Included in:
RedirectSafely
Defined in:
lib/version.rb,
lib/redirect_safely.rb

Constant Summary collapse

VERSION =
"1.0.0"

Instance Method Summary collapse

Instance Method Details

#make_safe(uri, default, options = {}) ⇒ Object



8
9
10
11
12
13
14
# File 'lib/redirect_safely.rb', line 8

def make_safe(uri, default, options = {})
  if uri.present? && safe?(uri, options)
    uri
  else
    default
  end
end

#safe?(uri_string, options = {}) ⇒ Boolean

Returns:

  • (Boolean)


16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/redirect_safely.rb', line 16

def safe?(uri_string, options = {})
  return false if uri_string =~ %r{///}

  uri = URI.parse(uri_string.to_s)

  if uri.path
    return false unless uri.path.start_with?('/')
    return false if uri.path =~ %r{[/\\][/\\]}
  end
  return false unless uri.scheme.nil? || ['http', 'https'].include?(uri.scheme)
  return false unless uri.userinfo.nil?
  return false if options[:path_match] &&
  (uri.path !~ options[:path_match] || File.absolute_path(uri.path) !~ options[:path_match])
  return false if options[:require_absolute] && uri.host.nil?
  return false if options[:require_ssl] && uri.scheme && uri.scheme != 'https'
  return false unless valid_host?(uri.host, options[:whitelist], options[:subdomains])

  true
rescue URI::InvalidURIError
  false
end