Class: Shrine::UrlSigner
- Inherits:
-
Object
- Object
- Shrine::UrlSigner
- Defined in:
- lib/shrine/plugins/derivation_endpoint.rb
Defined Under Namespace
Classes: InvalidSignature
Instance Attribute Summary collapse
-
#secret_key ⇒ Object
readonly
Returns the value of attribute secret_key.
Instance Method Summary collapse
-
#generate_signature(string) ⇒ Object
Uses HMAC-SHA-256 algorithm to generate a signature from the given string using the secret key.
-
#initialize(secret_key) ⇒ UrlSigner
constructor
A new instance of UrlSigner.
-
#sign_url(url) ⇒ Object
Returns a URL with the ‘signature` query parameter.
- #verify_signature(string, signature) ⇒ Object
-
#verify_url(url) ⇒ Object
Calculcates the signature from the URL and checks whether it matches the value in the ‘signature` query parameter.
Constructor Details
#initialize(secret_key) ⇒ UrlSigner
Returns a new instance of UrlSigner.
707 708 709 |
# File 'lib/shrine/plugins/derivation_endpoint.rb', line 707 def initialize(secret_key) @secret_key = secret_key end |
Instance Attribute Details
#secret_key ⇒ Object (readonly)
Returns the value of attribute secret_key.
705 706 707 |
# File 'lib/shrine/plugins/derivation_endpoint.rb', line 705 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.
748 749 750 |
# File 'lib/shrine/plugins/derivation_endpoint.rb', line 748 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
712 713 714 715 716 717 718 719 720 721 |
# File 'lib/shrine/plugins/derivation_endpoint.rb', line 712 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
738 739 740 741 742 743 744 |
# File 'lib/shrine/plugins/derivation_endpoint.rb', line 738 def verify_signature(string, signature) if signature.nil? fail InvalidSignature, "missing \"signature\" param" elsif 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.
727 728 729 730 731 732 733 734 735 736 |
# File 'lib/shrine/plugins/derivation_endpoint.rb', line 727 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 |