Sha256: 09e4b253afb3898f8e056fa9c2796f4c968a8c2b91c364892d46aeb6c234bfc8

Contents?: true

Size: 1.39 KB

Versions: 1

Compression:

Stored size: 1.39 KB

Contents

module GithubWebhook::Processor
  extend ActiveSupport::Concern

  included do
    before_filter :authenticate_github_request!, :only => :create
  end

  class SignatureError < StandardError; end
  class UnspecifiedWebhookSecretError < StandardError; end

  def create
    if self.respond_to? event
      self.send event, json_body
      head(:ok)
    else
      raise NoMethodError.new("GithubWebhooksController##{event} not implemented")
    end
  end

  def ping(payload)
    puts "[GithubWebhook::Processor] Hook ping received, hook_id: #{payload[:hook_id]}, #{payload[:zen]}"
  end

  private

  HMAC_DIGEST = OpenSSL::Digest.new('sha1')

  def authenticate_github_request!
    raise UnspecifiedWebhookSecretError.new unless defined?(self.class::WEBHOOK_SECRET)

    expected_signature = "sha1=#{OpenSSL::HMAC.hexdigest(HMAC_DIGEST, self.class::WEBHOOK_SECRET, request_body)}"
    if signature_header != expected_signature
      raise SignatureError.new "Actual: #{signature_header}, Expected: #{expected_signature}"
    end
  end

  def request_body
    @request_body ||= (
      request.body.rewind
      request.body.read
    )
  end

  def json_body
    @json_body ||= ActiveSupport::HashWithIndifferentAccess.new(JSON.load(request_body))
  end

  def signature_header
    @signature_header ||= request.headers['X-Hub-Signature']
  end

  def event
    @event ||= request.headers['X-GitHub-Event'].to_sym
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
github_webhook-0.1.1 lib/github_webhook/processor.rb