Class: Authsignal::Webhook
- Inherits:
-
Object
- Object
- Authsignal::Webhook
- Defined in:
- lib/authsignal/webhook.rb
Constant Summary collapse
- VERSION =
'v2'
Instance Attribute Summary collapse
-
#api_secret_key ⇒ Object
readonly
Returns the value of attribute api_secret_key.
Instance Method Summary collapse
- #construct_event(payload, signature, tolerance = DEFAULT_TOLERANCE) ⇒ Object
- #extract_signature_parts(value) ⇒ Object
-
#initialize(api_secret_key) ⇒ Webhook
constructor
A new instance of Webhook.
- #parse_signature(value) ⇒ Object
Constructor Details
#initialize(api_secret_key) ⇒ Webhook
Returns a new instance of Webhook.
15 16 17 |
# File 'lib/authsignal/webhook.rb', line 15 def initialize(api_secret_key) @api_secret_key = api_secret_key end |
Instance Attribute Details
#api_secret_key ⇒ Object (readonly)
Returns the value of attribute api_secret_key.
13 14 15 |
# File 'lib/authsignal/webhook.rb', line 13 def api_secret_key @api_secret_key end |
Instance Method Details
#construct_event(payload, signature, tolerance = DEFAULT_TOLERANCE) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/authsignal/webhook.rb', line 19 def construct_event(payload, signature, tolerance = DEFAULT_TOLERANCE) parsed_signature = parse_signature(signature) seconds_since_epoch = Time.now.to_i if tolerance.positive? && parsed_signature[:timestamp] < seconds_since_epoch - (tolerance * 60) raise InvalidSignatureError, 'Timestamp is outside the tolerance zone.' end hmac_content = "#{parsed_signature[:timestamp]}.#{payload}" computed_signature = OpenSSL::HMAC.digest( OpenSSL::Digest.new('sha256'), @api_secret_key, hmac_content ) computed_signature_base64 = Base64.strict_encode64(computed_signature).delete('=') match = false parsed_signature[:signatures].each do |sig| if sig == computed_signature_base64 match = true break end end raise InvalidSignatureError, 'Signature mismatch.' unless match JSON.parse(payload, symbolize_names: true) end |
#extract_signature_parts(value) ⇒ Object
60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/authsignal/webhook.rb', line 60 def extract_signature_parts(value) result = { timestamp: -1, signatures: [] } value.split(',').each do |item| key, val = item.split('=') next unless key && val result[:timestamp] = val.to_i if key == 't' result[:signatures] << val if key == VERSION end result end |
#parse_signature(value) ⇒ Object
51 52 53 54 55 56 57 58 |
# File 'lib/authsignal/webhook.rb', line 51 def parse_signature(value) handle_invalid_signature unless value result = extract_signature_parts(value) handle_invalid_signature if result[:timestamp] == -1 || result[:signatures].empty? result end |