Class: UrlSigner

Inherits:
Object
  • Object
show all
Defined in:
lib/url_signer.rb

Constant Summary collapse

VERSION =
"0.2.0"
DEFAULT_HASH_LENGTH =
10
DEFAULT_SEPARATOR =
"_"

Instance Method Summary collapse

Constructor Details

#initialize(secret, options = {}) ⇒ UrlSigner

Initialize new url-signer

Parameter

secret (String)

secret for hashing

options (Hash)

possible options are:

- :hash_length (Integer):: set length of hash
- :separator (String):: set separator for hash in url


21
22
23
24
25
# File 'lib/url_signer.rb', line 21

def initialize(secret, options = {})
  self.secret = secret
  self.hash_length = options[:hash_length] || DEFAULT_HASH_LENGTH
  self.separator = options[:separator] || DEFAULT_SEPARATOR
end

Instance Method Details

#sign(url) ⇒ Object

signs a given url

Parameter

url (String)

whole URL to sign

Returns

signed URL (url with inserted hash)



35
36
37
38
39
# File 'lib/url_signer.rb', line 35

def sign(url)
  parsed_url = URI.parse(url)
  suffix = File.extname(parsed_url.path)
  parsed_url.to_s.gsub(/#{suffix}$/, "#{hash_with_separator(url)}#{suffix}")
end

#unsign(url) ⇒ Object

get url without hash (as it was before signing)

Parameter

url (String)

url with inserted hash

Returns

Returns a URL without hash (as it was before signing)



48
49
50
51
52
53
54
55
56
# File 'lib/url_signer.rb', line 48

def unsign(url)
  parsed_url = URI.parse(url)
  suffix = File.extname(parsed_url.path)
  # extract hash with separator from uri
  url_without_suffix = parsed_url.to_s.gsub(/#{suffix}$/, "")
  url_without_hash_and_suffix = url_without_suffix.gsub(/#{separator}.{#{hash_length}}$/, "")
  unsigned_url = "#{url_without_hash_and_suffix}#{suffix}"
  return unsigned_url
end

#valid?(url) ⇒ Boolean

validates a given URL

Parameter

url (String)

url to validate

Returns

true or false

Returns:

  • (Boolean)


65
66
67
# File 'lib/url_signer.rb', line 65

def valid?(url)
  hash(unsign(url)) == extract_hash(url)
end