Created
June 19, 2012 12:29
-
-
Save t-kashima/2953857 to your computer and use it in GitHub Desktop.
SinatraとOAuthとFacebook
This file contains hidden or 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
#!/usr/bin/env ruby | |
require 'rubygems' | |
require 'sinatra' | |
require 'koala' | |
configure do | |
APPLICATION_ID = "facebook_application_id" | |
APPLICATION_SECRET = "facebook_application_secret" | |
set :sessions, true | |
enable :sessions | |
end | |
def base_url | |
"#{request.scheme}://#{request.host}:#{request.port.to_s}" | |
end | |
before do | |
if session[:facebook_access_token] | |
@graph = Koala::Facebook::API.new(session[:facebook_access_token]) | |
else | |
@graph = nil | |
end | |
end | |
def oauth_consumer | |
Koala::Facebook::OAuth.new(APPLICATION_ID, APPLICATION_SECRET) | |
end | |
get '/' do | |
if @graph | |
@me = @graph.get_object('me') | |
erb %{ | |
<p><%= @me['name'] %></p> | |
<img src="<%= @graph.get_picture('me') %>" alt="profile image"> | |
} | |
else | |
erb %{ <a href="/request_token">OAuth Login</a> } | |
end | |
end | |
get '/request_token' do | |
callback_url = "#{base_url}/access_token" | |
Koala::Facebook::OAuth.new(APPLICATION_ID, APPLICATION_SECRET, callback_url) | |
redirect oauth_consumer.url_for_oauth_code(:callback => callback_url) | |
end | |
get '/access_token' do | |
if params[:code] | |
callback_url = "#{base_url}/access_token" | |
session[:facebook_access_token] = oauth_consumer.get_access_token(params[:code], :redirect_uri => callback_url) | |
redirect '/' | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment