5 require 'google/api_client'
7 use Rack::Session::Pool, :expire_after => 86400 # 1 day
9 # Set up our token store
10 DataMapper.setup(:default, 'sqlite::memory:')
12 include DataMapper::Resource
15 property :refresh_token, String
16 property :access_token, String
17 property :expires_in, Integer
18 property :issued_at, Integer
20 def update_token!(object)
21 self.refresh_token = object.refresh_token
22 self.access_token = object.access_token
23 self.expires_in = object.expires_in
24 self.issued_at = object.issued_at
29 :refresh_token => refresh_token,
30 :access_token => access_token,
31 :expires_in => expires_in,
32 :issued_at => Time.at(issued_at)
36 TokenPair.auto_migrate!
39 @client = Google::APIClient.new
40 @client.authorization.client_id = '245083617981.apps.googleusercontent.com'
41 @client.authorization.client_secret = 'pYelZCRjSa+iMezYENVScXFk'
42 @client.authorization.scope = 'https://www.googleapis.com/auth/buzz'
43 @client.authorization.redirect_uri = to('/oauth2callback')
44 @client.authorization.code = params[:code] if params[:code]
46 # Load the access token here if it's available
47 token_pair = TokenPair.get(session[:token_id])
48 @client.authorization.update_token!(token_pair.to_hash)
50 if @client.authorization.refresh_token && @client.authorization.expired?
51 @client.authorization.fetch_access_token!
53 @buzz = @client.discovered_api('buzz')
54 unless @client.authorization.access_token || request.path_info =~ /^\/oauth2/
55 redirect to('/oauth2authorize')
59 get '/oauth2authorize' do
60 redirect @client.authorization.authorization_uri.to_s, 303
63 get '/oauth2callback' do
64 @client.authorization.fetch_access_token!
65 # Persist the token here
66 token_pair = if session[:token_id]
67 TokenPair.get(session[:token_id])
71 token_pair.update_token!(@client.authorization)
73 session[:token_id] = token_pair.id
78 result = @client.execute(
79 @buzz.activities.list,
80 {'userId' => '@me', 'scope' => '@consumption', 'alt'=> 'json'}
82 status, _, _ = result.response
83 [status, {'Content-Type' => 'application/json'}, JSON.generate(result.data)]