Class: LlamaHair::WebhookValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/llamahair/server.rb

Overview

Validates incoming webhooks from the Llama API in Rails controllers

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ WebhookValidator

Returns a new instance of WebhookValidator.

Parameters:



11
12
13
# File 'lib/llamahair/server.rb', line 11

def initialize(options)
  @options = options
end

Instance Method Details

#verify(request) ⇒ Boolean

Verify a Rails request signature

Parameters:

  • request (ActionDispatch::Request)

    The Rails request object

Returns:

  • (Boolean)

    true if the signature is valid



18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/llamahair/server.rb', line 18

def verify(request)
  body = JSON.parse(request.raw_post, symbolize_names: true)
  return false unless body[:type] == "validate"

  data = "#{body[:timestamp]}#{body[:value]}"
  expected = OpenSSL::HMAC.hexdigest('SHA256', @options.secret, data)
  actual = request.headers['X-Webhook-Signature'] || request.headers['HTTP_X_WEBHOOK_SIGNATURE']

  return false unless actual
  ActiveSupport::SecurityUtils.secure_compare(expected, actual)
rescue JSON::ParserError, StandardError => e
  Rails.logger.error("Webhook verification failed: #{e.message}")
  false
end