Class: Shrine::UrlSigner

Inherits:
Object
  • Object
show all
Defined in:
lib/shrine/plugins/derivation_endpoint.rb

Defined Under Namespace

Classes: InvalidSignature

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(secret_key) ⇒ UrlSigner

Returns a new instance of UrlSigner.


708
709
710
# File 'lib/shrine/plugins/derivation_endpoint.rb', line 708

def initialize(secret_key)
  @secret_key = secret_key
end

Instance Attribute Details

#secret_keyObject (readonly)

Returns the value of attribute secret_key.


706
707
708
# File 'lib/shrine/plugins/derivation_endpoint.rb', line 706

def secret_key
  @secret_key
end

Instance Method Details

#generate_signature(string) ⇒ Object

Uses HMAC-SHA-256 algorithm to generate a signature from the given string using the secret key.


749
750
751
# File 'lib/shrine/plugins/derivation_endpoint.rb', line 749

def generate_signature(string)
  OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secret_key, string)
end

#sign_url(url) ⇒ Object

Returns a URL with the `signature` query parameter


713
714
715
716
717
718
719
720
721
722
# File 'lib/shrine/plugins/derivation_endpoint.rb', line 713

def sign_url(url)
  path, query = url.split("?")

  params = Rack::Utils.parse_query(query.to_s)
  params.merge!("signature" => generate_signature(url))

  query = Rack::Utils.build_query(params)

  "#{path}?#{query}"
end

#verify_signature(string, signature) ⇒ Object


739
740
741
742
743
744
745
# File 'lib/shrine/plugins/derivation_endpoint.rb', line 739

def verify_signature(string, signature)
  if signature.nil?
    fail InvalidSignature, "missing \"signature\" param"
  elsif !Rack::Utils.secure_compare(signature, generate_signature(string))
    fail InvalidSignature, "provided signature does not match the calculated signature"
  end
end

#verify_url(url) ⇒ Object

Calculcates the signature from the URL and checks whether it matches the value in the `signature` query parameter. Raises `InvalidSignature` if the `signature` parameter is missing or its value doesn't match the calculated signature.


728
729
730
731
732
733
734
735
736
737
# File 'lib/shrine/plugins/derivation_endpoint.rb', line 728

def verify_url(url)
  path, query = url.split("?")

  params    = Rack::Utils.parse_query(query.to_s)
  signature = params.delete("signature")

  query = Rack::Utils.build_query(params)

  verify_signature("#{path}?#{query}", signature)
end