class Rack::TwilioValidator

Constants

VERSION

Public Class Methods

new(app, options = {}) click to toggle source
# File lib/rack/twilio-validator.rb, line 5
def initialize(app, options = {})
  @app = app
  @options = options
  @auth_token = options.fetch(:auth_token)
  @app
end

Public Instance Methods

_call(env) click to toggle source
# File lib/rack/twilio-validator.rb, line 16
def _call(env)
  @request = Rack::Request.new(env)

  if unprotected_path? || validate(env['HTTP_X_TWILIO_SIGNATURE'])
    @app.call(env)
  else
    response = ::Twilio::TwiML::Response.new do |r|
      r.Say("Middleware unable to authenticate request signature")
    end
    [401, { "Content-Type" => "application/xml" }, [response.text]]
  end
end
call(env) click to toggle source
# File lib/rack/twilio-validator.rb, line 12
def call(env)
  self.dup._call(env)
end

Private Instance Methods

formatted_url() click to toggle source

Twilio currently strips the port from https requests. See www.twilio.com/docs/security under ‘A Few Notes’ for more info

# File lib/rack/twilio-validator.rb, line 43
def formatted_url
  if @request.scheme == "https"
    @request.url.gsub(/:#{@request.port}/, '')
  else
    @request.url
  end
end
protected_path?() click to toggle source
# File lib/rack/twilio-validator.rb, line 31
def protected_path?
  protected_path = @options.fetch(:protected_path, "/")
  @request.path =~ %r/^#{protected_path}/
end
unprotected_path?() click to toggle source
# File lib/rack/twilio-validator.rb, line 36
def unprotected_path?
  ! protected_path?
end
validate(signature) click to toggle source
# File lib/rack/twilio-validator.rb, line 51
def validate(signature)
  validator = ::Twilio::Util::RequestValidator.new(@auth_token)
  validator.validate(formatted_url, @request.params, signature)
end