Class: Hull::Middlewares::Hook

Inherits:
Object
  • Object
show all
Defined in:
lib/hull/middlewares/hook.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}, &handler) ⇒ Hook

Returns a new instance of Hook.



9
10
11
12
13
14
15
16
17
# File 'lib/hull/middlewares/hook.rb', line 9

def initialize app, options={}, &handler
  @app      = app
  @options  = options
  if block_given?
    @handler  = handler
  elsif options[:handler]
    @handler = options[:handler]
  end
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



7
8
9
# File 'lib/hull/middlewares/hook.rb', line 7

def options
  @options
end

Instance Method Details

#call(env) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/hull/middlewares/hook.rb', line 19

def call env
  path = options[:path] || "/__hull-hooks__"
  if env['PATH_INFO'] == path && valid?(env)
    begin
      request   = Rack::Request.new(env)
      event     = JSON.parse(request.body.read)
      response  = (@handler.call(event, request) || "ok").to_s
      [200, { 'Content-Type' => 'text/html' }, [response]]
    rescue => err
      [500, { 'Content-Type' => 'text/html' }, ["Invalid Request: #{err.inspect}"]]
    end
  else
    @app.call(env)
  end
end

#valid?(env) ⇒ Boolean

Returns:

  • (Boolean)


35
36
37
38
39
40
41
# File 'lib/hull/middlewares/hook.rb', line 35

def valid? env
  body = env['rack.input'].read
  env['rack.input'].rewind
  timestamp, nonce, signature = (env['HTTP_HULL_SIGNATURE'] || "").split('.')
  data    = [timestamp, nonce, body].join("-")
  signature == OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('sha1'), options[:secret], data)
end