Skip to content

Instantly share code, notes, and snippets.

@rupakg
Forked from therealadam/Gemfile
Created November 12, 2011 08:14
Show Gist options
  • Save rupakg/1360233 to your computer and use it in GitHub Desktop.
Save rupakg/1360233 to your computer and use it in GitHub Desktop.
An example of how to authorize your app with Punchtab's OAuth2 API
begin
# Require preresolved locked gems
require ::File.expand_path('.bundle/environment', __FILE__)
rescue LoadError
# Fallback on resolving at runtime
require 'rubygems'
require 'bundler'
Bundler.setup
end
require 'sinatra/base'
require 'oauth2'
require 'json'
class App < Sinatra::Base
set :sessions, true
get '/' do
if session[:access_token]
redirect '/auth/punchtab/test'
else
"Why not authenticate with <a href=\'/auth/punchtab\'>Punchtab</a>?"
end
end
get '/auth/punchtab' do
auth_url = client.auth_code.authorize_url(:redirect_uri => redirect_uri)
### Do this as Punchtab needs response_type=token
auth_url.gsub!("?response_type=code&", "?response_type=token&")
redirect(auth_url)
end
get '/auth/punchtab/callback' do
if (params = {} || params[:access_token] == "")
"PunchTab only supports authentication via Javascript client-side applications."
else
begin
session[:access_token] = client.auth_code.get_token(params[:access_token], :redirect_uri => redirect_uri)
rescue OAuth2::Error => err
return "OAuth2 Error: #{err.backtrace}"
end
if session[:access_token]
redirect '/auth/punchtab/test'
else
"Error retrieving access token."
end
end
end
get '/auth/punchtab/test' do
if session[:access_token]
connection = OAuth2::AccessToken.new(client, session[:access_token])
headers = {'Accept' => 'application/json'}
connection.get('/v1/leaderboard', {}, headers).inspect
else
redirect '/auth/punchtab'
end
end
protected
def client
api_key = ENV['API_KEY']
api_secret = ENV['API_SECRET']
options = {
:site => ENV['SITE'] || 'https://www.punchtab.com',
:authorize_url => ENV['AUTHORIZE_URL'] || '/oauth/authorize'
}
OAuth2::Client.new(api_key, api_secret, options)
end
def redirect_uri
uri = URI.parse(request.url)
uri.path = '/auth/punchtab/callback'
uri.query = nil
uri.to_s
end
end
run App
source :rubygems
gem 'sinatra', '1.0'
gem 'oauth2'
gem 'json'
group :development do
gem 'shotgun'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment