Skip to content

Instantly share code, notes, and snippets.

@aquarla
Created May 30, 2011 07:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aquarla/998545 to your computer and use it in GitHub Desktop.
Save aquarla/998545 to your computer and use it in GitHub Desktop.
Facebook認証サンプルの雛形
require 'rubygems'
require 'sinatra'
require 'oauth2'
require 'securerandom'
use Rack::Session::Cookie,
:expire_after => 86400,
:secret => SecureRandom.hex(32)
APP_ID='1111111111111' # FacebookアプリのアプリケーションID
APP_SECRET='aaaaaaaaaaaaaaaaaa' # Facebookアプリのsecret
REDIRECT_URI='http://[ドメイン名]/callback' # リダイレクト用URIを指定する
SCOPE='offline_access' # 呼び出すAPIに応じて変える
@@client = OAuth2::Client.new(APP_ID, APP_SECRET,
{:site => 'https://graph.facebook.com', :ssl => {:verify => false}, :parse_json => true})
get '/' do
if session[:access_token]
access_token = OAuth2::AccessToken.new(@@client, session[:access_token])
@me = access_token.get("/me")
end
erb :index
end
get '/login' do
redirect @@client.web_server.authorize_url(:redirect_uri => REDIRECT_URI, :scope => SCOPE)
end
get '/logout' do
session[:access_token] = nil
redirect '/'
end
get '/callback' do
if params[:code]
access_token = @@client.web_server.get_access_token(params[:code], :redirect_uri => REDIRECT_URI)
session[:access_token] = access_token.token
redirect '/'
end
end
helpers do
# ログアウト状態のときはログインリンク、ログイン状態のときはログアウトリンク
def link_to_login_or_logout
if session[:access_token]
%Q(<a href="/logout">ログアウト</a>)
else
%Q(<a href="/login">ログイン</a>)
end
end
# Hashをhtml table形式で出力する
def to_html_table(hash)
result = ""
if hash
result << "<table>"
hash.each do |key, value|
result << "<tr>"
result << "<th>#{key}</th>"
result << "<td>"
if value.is_a?(Hash)
result << to_html_table(value)
elsif value.is_a?(Array)
value.each do |v|
result << to_html_table(v)
end
else
result << "#{value}"
end
result << "</td>"
result << "</tr>"
end
result << "</table>"
end
result
end
end
__END__
__DATA__
@@ index
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<%= link_to_login_or_logout %>
<%= to_html_table(@me) %>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment