Skip to content

Instantly share code, notes, and snippets.

@iainbeeston
Created March 6, 2012 23:43
Show Gist options
  • Save iainbeeston/1989825 to your computer and use it in GitHub Desktop.
Save iainbeeston/1989825 to your computer and use it in GitHub Desktop.
Facebook real-time updates Rails Metal controller.
module ApplicationHelper
def signature(str, key = nil)
key ||= CONFIG['facebook']['secret'] if defined?(CONFIG)
OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('sha1'), key, str)
end
end
class FacebookController < ActionController::Metal
include ApplicationHelper
def notify
if payload?
# do something clever with the request body.
respond_with 200
else
respond_with 400
end
end
def verify
if params['hub.mode'] == 'subscribe' && params['hub.verify_token'] == CONFIG['facebook']['verify']
respond_with params['hub.challenge'], 200
else
respond_with 400
end
end
private
def body
@body ||= request.body.read
end
def payload?
request.headers['HTTP_X_HUB_SIGNATURE'] =~ /^sha1=([0-9a-z]{40})$/
$1 && signature(body) == $1
end
def respond_with(body = '', status)
self.response_body = body
self.status = status
end
end
Facebook::Application.routes.draw do
match 'facebook', to: FacebookController.action(:notify), via: :post, as: :facebook_notify
match 'facebook', to: FacebookController.action(:verify), via: :get, as: :facebook_verify
end
@leoromanovsky
Copy link

Stumbled upon this gist and it was very helpful - thanks very much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment