How do I authorize a service account for Google Calendar API in Ruby?
OK I found a way.
https://developers.google.com/api-client-library/ruby/auth/service-accounts
require 'google/apis/calendar_v3'
require 'googleauth'
# Get the environment configured authorization
scopes = ['https://www.googleapis.com/auth/calendar']
authorization = Google::Auth.get_application_default(scopes)
# Clone and set the subject
auth_client = authorization.dup
auth_client.sub = 'myemail@mydomain.com'
auth_client.fetch_access_token!
# Initialize the API
service = Google::Apis::CalendarV3::CalendarService.new
service.authorization = auth_client
# Fetch the next 10 events for the user
calendar_id = 'primary'
response = service.list_events(calendar_id,
max_results: 10,
single_events: true,
order_by: 'startTime',
time_min: Time.now.iso8601)
puts 'Upcoming events:'
puts 'No upcoming events found' if response.items.empty?
response.items.each do |event|
start = event.start.date || event.start.date_time
puts "- #{event.summary} (#{start})"
end
And
>set GOOGLE_APPLICATION_CREDENTIALS=client_secrets.json
C:\Users\Chloe\workspace>ruby quickstart.rb
Upcoming events:
- Test (2018-05-17)
- SSL Certificate for CMS (2019-02-13)
But I wonder where it saves the refresh token and access token? All I have to do now is make it work for ephemeral file systems like Heroku and store the tokens in the database.
How to set up Google Calendar API using Ruby client for server to server applications
AUTHORIZATION SETUP FOR GOOGLE CALENDAR
Somewhat helpful link: https://developers.google.com/api-client-library/ruby/
- Go to: https://console.developers.google.com/iam-admin/projects
- Click "+Create Project"
- Enter a "Project name" and "Project ID" and click "Create"
- Under "Library" select "Calendar API"
- Click ">Enable"
- Return to: https://console.developers.google.com/iam-admin/projects
- Click "Service Accounts"
- Click "Select a project"
- Choose your project and click "Open"
- Click "+Create Service Account"
- Enter a "Service account name" and choose a "Role" (I chose "editor")
- Check "Furnish a new private key"
- Click "Create"
A JSON file will be downloaded to your computer.
Move this file to some place accessible by your application and rename it to "google_api.json" (or whatever you want as long as it matches the correct path below). Ensure that only the application can access this file (it contains a private key).
- Copy the "client_email" from the JSON file and go to the settings of the
Google Calendar that you want this application to access. - Click "Calendars"
- Choose the correct calendar
- Click "Change sharing settings" found under "Calendar Address:"
- Add the email you copied and select the proper permission
- Click "Save"
- Copy the "Calendar ID" to the right of "Calendar Address:"
- You can hardcode the calendar ID below or put it in YAML file or as an environmental variable.
Here is a sample file to authorize and access the Googe Calendar API:
# http://www.rubydoc.info/github/google/google-api-ruby-client/Google/Apis/CalendarV3
require 'googleauth'
require 'google/apis/calendar_v3'
class MyApp::GoogleCalendar
def initialize
authorize
end
def service
@service
end
def events(reload=false)
# NOTE: This is just for demonstration purposes and not complete.
# If you have more than 2500 results, you'll need to get more than
# one set of results.
@events = nil if reload
@events ||= service.list_events(calendar_id, max_results: 2500).items
end
private
def calendar_id
@calendar_id ||= # The calendar ID you copied in step 20 above (or some reference to it).
end
def authorize
calendar = Google::Apis::CalendarV3::CalendarService.new
calendar.client_options.application_name = 'App Name' # This is optional
calendar.client_options.application_version = 'App Version' # This is optional
# An alternative to the following line is to set the ENV variable directly
# in the environment or use a gem that turns a YAML file into ENV variables
ENV['GOOGLE_APPLICATION_CREDENTIALS'] = "/path/to/your/google_api.json"
scopes = [Google::Apis::CalendarV3::AUTH_CALENDAR]
calendar.authorization = Google::Auth.get_application_default(scopes)
@service = calendar
end
end
So now you can call cal = MyApp::GoogleCalendar.new
and get the events with cal.events
. Or you can make calls directly with cal.service.some_method(some_args)
, rather than creating methods in this file.
Related Topics
Ruby: How to Iterate Over an Array of Hashes and Return the Values in a Single String
Bcrypt Error: Devise Ruby 2.0 and Rails 4.0
How to Install (Build) Ruby 1.9.3 on Osx Lion
Creating Signature and Nonce for Oauth (Ruby)
What's the Best Way to Deploy a Jruby on Rails Application to Tomcat
How to Install Ruby on Rails 3.0 on Ubuntu 10.10
Rails: Money Gem Converts All Amounts to Zero
Set Path for Original Images Using Paperclip in Rails
Cannot Connect to Remote Db Using Ssh Tunnel and Activerecord
Check If Two Arrays Have the Same Contents (In Any Order)
Rspec 3 How to Test Flash Messages
Array.Join("\N") Not the Way to Join with a Newline
How to Convert a Comma-Separated String into an Array
How to Use Array#Delete While Iterating Over the Array
Does Dependency Injection Exist in Rails
How to Password-Protect My /Sidekiq Route (I.E. Require Authentication for the Sidekiq::Web Tool)