Class: Rack::SignalwireWebhookAuthentication

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/signalwire_webhook_authentication.rb

Constant Summary collapse

FORM_URLENCODED_MEDIA_TYPE =
Rack::MediaType.type('application/x-www-form-urlencoded')

Instance Method Summary collapse

Constructor Details

#initialize(app, private_key, *paths, &private_key_lookup) ⇒ SignalwireWebhookAuthentication

Returns a new instance of SignalwireWebhookAuthentication.



9
10
11
12
13
14
# File 'lib/rack/signalwire_webhook_authentication.rb', line 9

def initialize(app, private_key, *paths, &private_key_lookup)
  @app = app
  @private_key = private_key
  define_singleton_method(:get_private_key, private_key_lookup) if block_given?
  @path_regex = Regexp.union(paths)
end

Instance Method Details

#call(env) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/rack/signalwire_webhook_authentication.rb', line 16

def call(env)
  return @app.call(env) unless env['PATH_INFO'].match(@path_regex)
  request = Rack::Request.new(env)
  original_url = request.url
  params = extract_params!(request)
  private_key = @private_key || get_private_key(params['AccountSid'])
  validator = Signalwire::Webhook::ValidateRequest.new(private_key)
  signature = env['HTTP_X_SIGNALWIRE_SIGNATURE'] || env['HTTP_X_TWILIO_SIGNATURE'] || ''
  if validator.validate(original_url, params, signature)
    @app.call(env)
  else
    [
      403,
      { 'Content-Type' => 'text/plain' },
      ['Signalwire Request Validation Failed.']
    ]
  end
end