Created
November 1, 2013 18:45
-
-
Save patbenatar/7269948 to your computer and use it in GitHub Desktop.
Some code to help with running a Rails app within the Facebook app iframe (not page tab)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ApplicationController < ActionController::Base | |
before_filter :sign_in_with_facebook_signed_request | |
protect_from_forgery | |
private | |
def sign_in_with_facebook_signed_request | |
return true unless params[:signed_request] | |
signed_request_data = FacebookHelper.decode_signed_request(params[:signed_request]) | |
uid = signed_request_data["user_id"] | |
user = User.find_or_create_for_facebook_uid(uid) | |
sign_in user | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module FacebookHelper | |
class << self | |
def base64_url_decode(str) | |
encoded_str = str.gsub("-", "+").gsub("_", "/") | |
encoded_str += "=" while !(encoded_str.size % 4).zero? | |
Base64.decode64(encoded_str) | |
end | |
def decode_signed_request(str) | |
encoded_sig, payload = str.split(".") | |
ActiveSupport::JSON.decode base64_url_decode(payload) | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Rack middleware that converts POST requests from Facebook to GET request. | |
# When there is a signed_parameter in the request params, this is a request iniated by the top Facebook frame | |
# It will be sent as a POST request that we want to convert to a GET request to keep the app restful | |
# Note: put this before your app is ran in config.ru | |
# See for details : http://blog.coderubik.com/?p=178 | |
module Rack | |
class FacebookPostInterceptor | |
def initialize(app) | |
@app = app | |
end | |
def call(env) | |
request = Request.new(env) | |
if request.POST["signed_request"] && request.params["_method"].blank? | |
env["REQUEST_METHOD"] = 'GET' | |
end | |
return @app.call(env) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment