Question

I could successfully push events into Google calendar using the below mentioned code. The below controller code refreshes token every time I try to push events. It's working fine.

 class Add2gcalendarController < ApplicationController

  before_filter :authenticate_user!   
  def push  
       event = {'summary' => 'Appointment','location' => 'Somewhere','start' => {'dateTime' => '2014-06-03T10:00:00.000-07:00'},'end' => {'dateTime' => '2014-06-03T10:25:00.000-07:00'}}
          client = Google::APIClient.new
          client.authorization.client_id =ENV["GOOGLE_KEY"]
          client.authorization.client_secret = ENV["GOOGLE_SECRET"]
          client.authorization.grant_type = 'refresh_token'
          client.authorization.refresh_token = saved_refresh_token
          client.authorization.fetch_access_token!  
          service = client.discovered_api('calendar', 'v3')                   
          @result = client.execute(
        :api_method => service.events.insert,
        :parameters => {'calendarId' => 'primary'},
        :body => JSON.dump(event), # where cal is the object containing at least "summary".
        :headers => {'Content-Type' => 'application/json'})

 end

My questions:

  1. Is it a good practice to refresh token every-time i try to push events,irrespective of whether the token got expired or not?

  2. Was there a limit on generating access tokens using refresh token?

Was it helpful?

Solution

There's really no reason to force refresh of the access token if it's not expired. Doing so is inefficient for your app (user has to wait for another HTTP call) and, taken to an extreme (refreshing constantly or for every single API call) can result in 5xx errors from Google.

If the ruby on rails library is handling refresh for you automatically I'd recommend just letting it handle the refresh for you entirely. The libraries generally are written by Googlers who know best practice of OAuth handling.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top