Skip to content

Instantly share code, notes, and snippets.

@georgi
Created March 8, 2012 12:37
Show Gist options
  • Save georgi/2000824 to your computer and use it in GitHub Desktop.
Save georgi/2000824 to your computer and use it in GitHub Desktop.
Facebook Mobile Hack Demo
# Login endpoint for client side flow
# Takes a token paremeter and creates a user if necessary
post "/auth" do
client = Facebook.exchange_token(params[:token])
user = User.from_facebook(client)
session[:user] = user.uid
redirect '/'
end
class Facebook
# Refresh short-lived token with a long-lived one
def self.exchange_token(token)
res = access_token(:grant_type => "fb_exchange_token", :fb_exchange_token => token)
new(parse_token(res.body))
end
end
# Shows a list of recent plays on SoundCloud
get "/" do
begin
if user
# Logged in users have a Facebook connection
@actions = user.facebook.get('/me/soundcloud:listen')['data']
end
# rendering html template
erb :index
# Access Token is expired, so we reauth the user on Facebook
rescue Facebook::OAuthException
redirect auth_url
end
end
$(function() {
FB.init({
appId : App.appId,
cookie : true,
oauth : true
});
// If user is not logged in, we try to authenticate from Facebook.
if (!App.userId) {
// Query Facebook API for authentication data
FB.getLoginStatus(function(response) {
// The user already connected to the app, so we just need to
// send the access token to login the user.
if (response.status === 'connected') {
$('#access-token').val(response.authResponse.accessToken);
$('#auth-form').submit();
}
else {
// The user hasn't connected yet, so we redirect to the
// Facebook Authentication Dialog.
window.location = App.authUrl;
// https://www.facebook.com/dialog/oauth?scope=user_actions:soundcloud&redirect_uri=https://mobile-hack.herokuapp.com/auth
}
});
}
});
# Callback endpoint for server side flow
# Takes a OAuth code parameter and creates a user if necessary
get "/auth" do
client = Facebook.exchange_code(params[:code], url('/auth'))
user = User.from_facebook(client)
session[:user] = user.uid
redirect '/'
end
class Facebook
# Request access token for given authorization code
def self.exchange_code(code, redirect_uri)
res = access_token(:code => code, :redirect_uri => redirect_uri)
new(parse_token(res.body))
end
end
class Soundcloud
APP_ID = 'YOUR_CLIENT_ID'
def self.http(domain = "api.soundcloud.com")
Net::HTTP.new(domain, 80)
end
def self.get(path, params={})
JSON.parse(http.get(path + '.json?' + urlencode_hash({ :client_id => APP_ID }.merge(params))).body)
end
# Returns an embeddable player
def self.oembed(url)
JSON.parse(http('soundcloud.com').get('/oembed?' + urlencode_hash(:format => 'json', :url => url)).body)
rescue JSON::ParserError
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment