Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
OAuth Consumer Example with Sinatra: http://www.machu.jp/diary/20090818.html#p01
require 'rubygems'
require 'sinatra'
require 'oauth'
require 'twitter'
helpers do
include Rack::Utils
alias_method :h, :escape_html
end
configure do
use Rack::Session::Cookie, :secret => Digest::SHA1.hexdigest(rand.to_s)
KEY = "twitter_consumer_key"
SECRET = "twitter_consumer_secret"
end
before do
if session[:access_token]
twitter_oauth = Twitter::OAuth.new(KEY, SECRET)
twitter_oauth.authorize_from_access(
session[:access_token], session[:access_token_secret])
@twitter = Twitter::Base.new(twitter_oauth)
else
@twitter = nil
end
end
template :layout do
<<-EOS
<html>
<head><title>OAuth Example with Sinatra</title></head>
<body>
<%= yield %>
</body>
</html>
EOS
end
def base_url
default_port = (request.scheme == "http") ? 80 : 443
port = (request.port == default_port) ? "" : ":#{request.port.to_s}"
"#{request.scheme}://#{request.host}#{port}"
end
def oauth_consumer
OAuth::Consumer.new(KEY, SECRET, :site => "http://twitter.com")
end
get '/' do
erb %{ <a href="/request_token">OAuth Login</a> }
end
get '/request_token' do
callback_url = "#{base_url}/access_token"
request_token = oauth_consumer.get_request_token(:oauth_callback => callback_url)
session[:request_token] = request_token.token
session[:request_token_secret] = request_token.secret
redirect request_token.authorize_url
end
get '/access_token' do
request_token = OAuth::RequestToken.new(
oauth_consumer, session[:request_token], session[:request_token_secret])
begin
@access_token = request_token.get_access_token(
{},
:oauth_token => params[:oauth_token],
:oauth_verifier => params[:oauth_verifier])
rescue OAuth::Unauthorized => @exception
return erb %{ oauth failed: <%=h @exception.message %> }
end
session[:access_token] = @access_token.token
session[:access_token_secret] = @access_token.secret
erb %{
oauth success!
<dl>
<dt>access token</dt>
<dd><%=h @access_token.token %></dd>
<dt>secret</dt>
<dd><%=h @access_token.secret %></dd>
</dl>
<a href="/timeline">go timeline</a>
}
end
get '/timeline' do
redirect '/' unless @twitter
erb %{
<dl>
<% @twitter.friends_timeline.each do |twit| %>
<dt><%= twit.user.name %></dt>
<dd><%= twit.text %></dd>
<% end %>
</dl>
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment