Sha256: ce8aea2f8d5722b61922ac980f2f6b7c88c58774b881c217b49a66562668bf0d

Contents?: true

Size: 1.13 KB

Versions: 2

Compression:

Stored size: 1.13 KB

Contents

require 'sinatra'
require 'rack/auth/basic'
require 'base64'
require 'json'

module Routemaster
  class Receiver
    def initialize(app, options = {})
      @app     = app
      @path    = options[:path]
      @uuid    = options[:uuid]
      @handler = options[:handler]
    end

    def call(env)
      catch :forward do
        throw :forward unless _intercept_endpoint?(env)
        return [401, {}, []] unless _has_auth?(env)
        return [403, {}, []] unless _valid_auth?(env)
        return [400, {}, []] unless payload = _extract_payload(env)

        @handler.on_events(payload)
        return [204, {}, []]
      end
      @app.call(env)
    end

    private

    def _intercept_endpoint?(env)
      env['PATH_INFO'] == @path && env['REQUEST_METHOD'] == 'POST'
    end

    def _has_auth?(env)
      env.has_key?('HTTP_AUTHORIZATION')
    end

    def _valid_auth?(env)
      Base64.
        decode64(env['HTTP_AUTHORIZATION'].gsub(/^Basic /, '')).
        split(':').first == @uuid
    end

    def _extract_payload(env)
      return unless env['CONTENT_TYPE'] == 'application/json'
      JSON.parse(env['rack.input'].read)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
routemaster-client-0.0.2 routemaster/receiver.rb
routemaster-client-0.0.1 routemaster/receiver.rb