Skip to content

Instantly share code, notes, and snippets.

@sabril
Created October 21, 2014 22:52
Show Gist options
  • Save sabril/d04b865600e0460174a6 to your computer and use it in GitHub Desktop.
Save sabril/d04b865600e0460174a6 to your computer and use it in GitHub Desktop.
How to refresh Google token
require 'google/api_client'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/installed_app'
class User < ActiveRecord::Base
def save_google_credentials(omniauth, params)
if omniauth["credentials"]["refresh_token"]
self.google_access_token = omniauth["credentials"]["token"]
self.google_refresh_token = omniauth["credentials"]["refresh_token"]
self.google_token_expires_at = Time.now.to_i + 3600
save
end
end
def refresh_token
data = {
:client_id => ENV['GOOGLE_CLIENT_ID'],
:client_secret => ENV['GOOGLE_SECRET'],
:refresh_token => google_refresh_token,
:grant_type => "refresh_token"
}
@response = ActiveSupport::JSON.decode(RestClient.post "https://accounts.google.com/o/oauth2/token", data)
if @response["access_token"].present?
self.google_token_expires_at = Time.now.to_i + 3600
self.google_access_token = @response["access_token"]
save
else
# No Token
puts "No Token :("
end
rescue RestClient::BadRequest => e
# Bad request
puts "Error: bad request :("
end
def revoke_google_token
@response = RestClient.get "https://accounts.google.com/o/oauth2/revoke?token=#{google_refresh_token}"
self.google_refresh_token = nil
self.google_access_token = nil
self.google_token_expires_at = nil
save
rescue RestClient::BadRequest => e
# Bad request
puts "Error: bad request :("
end
def access_token_expired?
google_token_expires_at.to_i <= Time.now.to_i
end
def get_calendar(start_date = Date.today)
refresh_token if access_token_expired?
if google_access_token
client = Google::APIClient.new(:application_name => 'My App', :application_version => '1.0.0')
calendar = client.discovered_api('calendar', 'v3')
client_secrets = Google::APIClient::ClientSecrets.load(ENV['GOOGLE_SECRET_FILE'])
client.authorization = client_secrets.to_authorization
client.authorization.scope = 'https://www.googleapis.com/auth/calendar'
auth = client.authorization
auth.access_token = google_access_token
auth.refresh_token = google_refresh_token
min_time= start_date.at_beginning_of_week.to_time.utc.iso8601
max_time= start_date.at_end_of_week.to_time.utc.iso8601
result = client.execute(
:api_method => calendar.events.list,
:parameters => {'calendarId' => 'primary', 'singleEvents' => true, "timeMin" => min_time, "timeMax" => max_time, "fields" => "items(start,end,transparency)"},
:authorization => auth
)
self.google_calendars = {"items" => result.data["items"].to_json}
save
end
rescue
Rails.logger.info "Error"
end
def google_events
JSON.parse(google_calendars["items"]) rescue []
end
def google_busy_time(tz=nil)
Time.zone = tz || timezone
#google_events.map{|e| Time.zone.parse(e["start"]["dateTime"]).strftime("%Y-%m-%d %H:00")} rescue []
# transparency = transparent if available
google_events.map{|e|
e["transparency"].nil? ?
[
e["start"]["dateTime"] != nil ? Time.zone.parse(e["start"]["dateTime"]).strftime("%Y-%m-%d %H:%M").to_time.to_i : Time.zone.parse(e["start"]["date"]).strftime("%Y-%m-%d %H:%M").to_time.to_i,
e["end"]["dateTime"] != nil ? Time.zone.parse(e["end"]["dateTime"]).strftime("%Y-%m-%d %H:%M").to_time.to_i : Time.zone.parse(e["end"]["date"]).strftime("%Y-%m-%d %H:%M").to_time.to_i
] : [0,0]
}
rescue
[]
end
def google_debug_time
google_busy_time.map {|e| [Time.at(e[0]), Time.at(e[1])]}
end
def debug_busy_time
existing_bookings_time.map {|e| [Time.at(e[0]), Time.at(e[1])]}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment