Sha256: 9c3db126de95a4176a8f7693f4663378b3e4c0dcde642e7ca025127c6456857c

Contents?: true

Size: 1.07 KB

Versions: 3

Compression:

Stored size: 1.07 KB

Contents

# frozen_string_literal: true

require 'rack'
require 'json'

module Hahamut
  # Handling HTTP Request
  class Handler
    SIGNATURE_HEADER = 'HTTP_X_BAHA_DATA_SIGNATURE'

    attr_reader :request, :response

    def initialize(env)
      @request = Rack::Request.new(env)
    end

    def process
      return invalid_client if client.nil?
      return invalid_signature unless valid_signature?

      Manager.handle(client, Event.new(body))

      Rack::Response.new([], 204)
    end

    def body
      @body ||= JSON.parse(raw)
    end

    def client
      Manager.find(body['botid'])
    end

    def raw
      return @raw unless @raw.nil?

      @raw = @request.body.read
      @request.body.rewind
      @raw
    end

    private

    def invalid_signature
      Rack::Response.new([], 401)
    end

    def invalid_client
      Rack::Response.new([], 404)
    end

    def valid_signature?
      return false unless @request.has_header?(SIGNATURE_HEADER)

      signature = @request.get_header(SIGNATURE_HEADER)
      Signature.new(client.secret, raw).match?(signature)
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
hahamut-0.1.2 lib/hahamut/handler.rb
hahamut-0.1.1 lib/hahamut/handler.rb
hahamut-0.1.0 lib/hahamut/handler.rb