class Castle::Webhooks::Verify

Verify a webhook

Public Class Methods

call(webhook, config = nil) click to toggle source

Checks if webhook is valid @param webhook [Request] @param config [Castle::Configuration, Castle::SingletonConfiguration, nil]

# File lib/castle/webhooks/verify.rb, line 11
def call(webhook, config = nil)
  config ||= Castle.config
  expected_signature = compute_signature(webhook, config)
  signature = webhook.env['HTTP_X_CASTLE_SIGNATURE']
  verify_signature(signature, expected_signature)
end

Private Class Methods

compute_signature(webhook, config) click to toggle source

Computes a webhook signature using provided user_id @param webhook [Request] @param config [Castle::Configuration, Castle::SingletonConfiguration] @return [String]

# File lib/castle/webhooks/verify.rb, line 24
def compute_signature(webhook, config)
  Base64.encode64(
    OpenSSL::HMAC.digest(
      OpenSSL::Digest.new('sha256'),
      config.api_secret,
      Castle::Core::ProcessWebhook.call(webhook, config)
    )
  ).strip
end
verify_signature(signature, expected_signature) click to toggle source

Check if the signatures are matching @param signature [String] first signature to be compared @param expected_signature [String] second signature to be compared

# File lib/castle/webhooks/verify.rb, line 37
def verify_signature(signature, expected_signature)
  return if Castle::Utils::SecureCompare.call(signature, expected_signature)

  raise Castle::WebhookVerificationError, 'Signature not matching the expected signature'
end