Skip to content

Instantly share code, notes, and snippets.

@timwaters
Created November 8, 2011 12:04
Show Gist options
  • Save timwaters/1347596 to your computer and use it in GitHub Desktop.
Save timwaters/1347596 to your computer and use it in GitHub Desktop.
Simple GeoCommons and GeoIQ OAuth Sinatra App
require "rubygems"
require "sinatra"
require "oauth"
require "oauth/consumer"
require 'haml'
enable :sessions
# Simple Ruby Sinatra application for interacting with GeoIQ server
# You would need to either supply environment variables for key, secret and site or change them in this file.
# You should also change the urls in the "/" and "/perm" calls to ones that the user can access and one that the user cannot.
#
before do
session[:oauth] ||= {}
consumer_key = ENV["consumer_key"] || "CONSUMER_KEY"
consumer_secret = ENV["consumer_secret"] || "CONSUMER_SECRET"
site = ENV["consumer_site"] || "http://geocommons.com"
@consumer ||= OAuth::Consumer.new(consumer_key, consumer_secret, :site => site)
if !session[:oauth][:request_token].nil? && !session[:oauth][:request_token_secret].nil?
@request_token = OAuth::RequestToken.new(@consumer, session[:oauth][:request_token], session[:oauth][:request_token_secret])
end
if !session[:oauth][:access_token].nil? && !session[:oauth][:access_token_secret].nil?
@access_token = OAuth::AccessToken.new(@consumer, session[:oauth][:access_token], session[:oauth][:access_token_secret])
end
end
# gets the edit page for the user, You'd need to change the url
get "/" do
if @access_token
@user_edit_page = @access_token.get('/search?mh_query=&format=json&limit=2')
haml :index
else
'<a href="/request">Sign On</a>'
end
end
get '/allowed' do
if @access_token
end
end
# tries to access a resource that its not allowed to, you'd need to change the url
get '/perm' do
if @access_token
text = @access_token.get('/datasets/2454.json')
else
text = "not logged in"
end
URI.escape(text.inspect)
end
get "/request" do
@request_token = @consumer.get_request_token(:oauth_callback => "http://#{request.host}:4567/auth")
session[:oauth][:request_token] = @request_token.token
session[:oauth][:request_token_secret] = @request_token.secret
redirect @request_token.authorize_url
end
get "/auth" do
@access_token = @request_token.get_access_token :oauth_verifier => params[:oauth_verifier]
session[:oauth][:access_token] = @access_token.token
session[:oauth][:access_token_secret] = @access_token.secret
redirect "/"
end
get "/logout" do
session[:oauth] = {}
redirect "/"
end
__END__
@@ layout
%html
= yield
@@ index
%p #{@user_edit_page.body}
@@ profile
%p Welcome
%p You are now connected via Geoiq
%p session[:profile].inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment