-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcalender.rb
76 lines (62 loc) · 2.13 KB
/
calender.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
require 'rubygems'
require 'google/api_client'
require 'sinatra'
require 'logger'
enable :sessions
def logger; settings.logger end
def api_client; settings.api_client; end
def calendar_api; settings.calendar; end
def user_credentials
# Build a per-request oauth credential based on token stored in session
# which allows us to use a shared API client.
@authorization ||= (
auth = api_client.authorization.dup
auth.redirect_uri = to('/oauth2callback')
auth.update_token!(session)
auth
)
end
configure do
log_file = File.open('calendar.log', 'a+')
log_file.sync = true
logger = Logger.new(log_file)
logger.level = Logger::DEBUG
client = Google::APIClient.new
client.authorization.client_id = '819350760249-mb0kjvrb3ilk9c8q7o2oojkph3nnhl2f.apps.googleusercontent.com'
client.authorization.client_secret = 'kB7dHa3xROZot_9d_HtD621j'
client.authorization.scope = 'https://www.googleapis.com/auth/calendar'
calendar = client.discovered_api('calendar', 'v3')
set :logger, logger
set :api_client, client
set :calendar, calendar
end
before do
# Ensure user has authorized the app
unless user_credentials.access_token || request.path_info =~ /^\/oauth2/
redirect to('/oauth2authorize')
end
end
after do
# Serialize the access/refresh token to the session
session[:access_token] = user_credentials.access_token
session[:refresh_token] = user_credentials.refresh_token
session[:expires_in] = user_credentials.expires_in
session[:issued_at] = user_credentials.issued_at
end
get '/oauth2authorize' do
# Request authorization
redirect user_credentials.authorization_uri.to_s, 303
end
get '/oauth2callback' do
# Exchange token
user_credentials.code = params[:code] if params[:code]
user_credentials.fetch_access_token!
redirect to('/')
end
get '/' do
# Fetch list of events on the user's default calandar
result = api_client.execute(:api_method => settings.calendar.events.list,
:parameters => {'calendarId' => 'primary'},
:authorization => user_credentials)
[result.status, {'Content-Type' => 'application/json'}, result.data.to_json]
end