Skip to content

Instantly share code, notes, and snippets.

@uglyog
Created May 16, 2014 01:16
Show Gist options
  • Save uglyog/58c318a011febe381bf2 to your computer and use it in GitHub Desktop.
Save uglyog/58c318a011febe381bf2 to your computer and use it in GitHub Desktop.
require 'grape'
require 'models/event_repository'
require 'models/events_decorator'
require 'digest/md5'
class EventsApi < Grape::API
version 'v1', using: :accept_version_header
helpers do
def body_matches_content_md5(body)
content_md5 = request.env['HTTP_CONTENT_MD5']
body_md5 = Base64.encode64(Digest::MD5.digest(body)).chomp
body_md5 == content_md5
end
end
content_type :json, 'application/json'
default_format :json
parser :json, nil
# enable warden HMAC authentication
before do
env['warden'].authenticate! :scope => :hmac
end
desc 'singleEvent: Store a single Event'
post do
# Check that the MD5 for the body actually matches the header. This is important as the HMAC signature includes the MD5 checksum header, but the
# warden HMAC does not verify it matches the body
error!('Unauthorized - Content-MD5 header is required for POST', 401) unless body_matches_content_md5(env['api.request.body'])
event = Models::Event.new.extend(Models::EventDecorator).from_json(env['api.request.body'])
Models::EventRepository.instance.add_event(event)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment