4 # Copyright:: Copyright 2011 Google Inc.
5 # License:: All Rights Reserved.
6 # Original Author:: Bob Aman
7 # Maintainer:: Daniel Dobson (mailto:wolff@google.com)
8 # Maintainer:: Jenny Murphy (mailto:mimming@google.com)
12 require 'google/api_client'
13 require 'httpadapter/adapters/net_http'
16 use Rack::Session::Pool, :expire_after => 86400 # 1 day
19 # See README for getting API id and secret
22 set :oauth_client_id, 'oauth_client_id'
23 set :oauth_client_secret, 'oauth_client_secret'
25 if (settings.oauth_client_id == 'oauth_client_id')
26 puts 'See README for getting API id and secret. Server terminated.'
30 set :oauth_client_id, ARGV[0]
31 set :oauth_client_secret, ARGV[1]
34 # Configuration that you probably don't have to change
35 set :oauth_scopes, 'https://www.googleapis.com/auth/buzz'
43 def update_token!(object)
44 @refresh_token = object.refresh_token
45 @access_token = object.access_token
46 @expires_in = object.expires_in
47 @issued_at = object.issued_at
52 :refresh_token => @refresh_token,
53 :access_token => @access_token,
54 :expires_in => @expires_in,
55 :issued_at => Time.at(@issued_at)
60 # At the beginning of any request, make sure the OAuth token is available.
61 # If it's not available, kick off the OAuth 2 flow to authorize.
63 @client = Google::APIClient.new(
64 :authorization => :oauth_2,
65 :host => 'www.googleapis.com',
66 :http_adapter => HTTPAdapter::NetHTTPAdapter.new
69 @client.authorization.client_id = settings.oauth_client_id
70 @client.authorization.client_secret = settings.oauth_client_secret
71 @client.authorization.scope = settings.oauth_scopes
72 @client.authorization.redirect_uri = to('/oauth2callback')
73 @client.authorization.code = params[:code] if params[:code]
75 # Load the access token here if it's available
76 @client.authorization.update_token!(session[:token].to_hash)
79 @buzz = @client.discovered_api('buzz')
80 unless @client.authorization.access_token || request.path_info =~ /^\/oauth2/
81 redirect to('/oauth2authorize')
85 # Part of the OAuth flow
86 get '/oauth2authorize' do
91 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
92 <title>Google Ruby API Buzz Sample</title>
95 <header><h1>Google Ruby API Buzz Sample</h1></header>
97 <a class='login' href='#{@client.authorization.authorization_uri.to_s}'>Connect Me!</a>
104 # Part of the OAuth flow
105 get '/oauth2callback' do
106 @client.authorization.fetch_access_token!
107 unless session[:token]
108 token_pair = TokenPair.new
109 token_pair.update_token!(@client.authorization)
110 # Persist the token here
111 session[:token] = token_pair
116 # The method you're probably actually interested in. This one lists a page of your
117 # most recent activities
119 response = @client.execute(
120 @buzz.activities.list,
121 'userId' => '@me', 'scope' => '@consumption', 'alt'=> 'json'
123 status, headers, body = response
124 [status, {'Content-Type' => 'application/json'}, body]