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
signaturequery 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
signaturequery parameter.
Constructor Details
#initialize(secret_key) ⇒ UrlSigner
Returns a new instance of UrlSigner.
714 715 716 |
# File 'lib/shrine/plugins/derivation_endpoint.rb', line 714 def initialize(secret_key) @secret_key = secret_key end |
Instance Attribute Details
#secret_key ⇒ Object (readonly)
Returns the value of attribute secret_key.
712 713 714 |
# File 'lib/shrine/plugins/derivation_endpoint.rb', line 712 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.
755 756 757 |
# File 'lib/shrine/plugins/derivation_endpoint.rb', line 755 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
719 720 721 722 723 724 725 726 727 728 |
# File 'lib/shrine/plugins/derivation_endpoint.rb', line 719 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
745 746 747 748 749 750 751 |
# File 'lib/shrine/plugins/derivation_endpoint.rb', line 745 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.
734 735 736 737 738 739 740 741 742 743 |
# File 'lib/shrine/plugins/derivation_endpoint.rb', line 734 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 |