Class: Spree::AllowedOrigin

Inherits:
Object
  • Object
show all
Includes:
SingleStoreResource
Defined in:
app/models/spree/allowed_origin.rb

Constant Summary collapse

LOOPBACK_HOSTS =

Loopback/development hosts that match any port, so storing ‘localhost` keeps matching `localhost:3000`, `:4000`, etc.

%w[localhost 127.0.0.1 ::1 0.0.0.0].freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.parse_origin(url) ⇒ Hash?

Parses a URL into its comparable origin components, or nil when the URL is invalid or not http(s). The host is downcased and has a single trailing dot stripped, and the port is the URI default (80/443) when not explicitly given.

Parameters:

  • url (String)

    the URL to parse

Returns:

  • (Hash, nil)

    ‘{ scheme:, host:, port: }` or nil



25
26
27
28
29
30
31
32
33
# File 'app/models/spree/allowed_origin.rb', line 25

def self.parse_origin(url)
  uri = URI.parse(url.to_s)
  return nil unless uri.is_a?(URI::HTTP)
  return nil if uri.host.blank?

  { scheme: uri.scheme.downcase, host: uri.host.downcase.chomp('.'), port: uri.port }
rescue URI::InvalidURIError
  nil
end

Instance Method Details

#matches?(url) ⇒ Boolean

Returns true if the given URL’s origin matches this stored origin.

Scheme and host must match exactly (host comparison is case- and trailing-dot- insensitive). Port must also match, with the scheme default applied, so storing ‘shop.com` matches `shop.com:443`. Loopback/development hosts (LOOPBACK_HOSTS) are exempt from the port check, so `localhost` still matches `localhost:3000`, `:4000`, etc.

Parameters:

  • url (String)

    the candidate URL to check

Returns:

  • (Boolean)


45
46
47
48
49
50
51
52
53
# File 'app/models/spree/allowed_origin.rb', line 45

def matches?(url)
  candidate = self.class.parse_origin(url)
  allowed = self.class.parse_origin(origin)
  return false if candidate.nil? || allowed.nil?
  return false unless allowed[:scheme] == candidate[:scheme]
  return false unless allowed[:host] == candidate[:host]

  LOOPBACK_HOSTS.include?(allowed[:host]) || allowed[:port] == candidate[:port]
end