Skip to content

Instantly share code, notes, and snippets.

@holysugar
Created October 2, 2012 09:38
Show Gist options
  • Save holysugar/3817860 to your computer and use it in GitHub Desktop.
Save holysugar/3817860 to your computer and use it in GitHub Desktop.
google-drive-ruby with oauth sample
require 'google_drive'
require 'oauth2'
require 'json'
require 'pry'
# create in https://code.google.com/apis/console/
@client_id = ""
@client_secret = ""
@redirect_uri = "urn:ietf:wg:oauth:2.0:oob"
@file = "db.json"
def client
if @client_id.empty?
puts "First you need to create oauth client information in https://code.google.com/apis/console/"
exit 1
end
OAuth2::Client.new(
@client_id, @client_secret,
:site => "https://accounts.google.com",
:token_url => "/o/oauth2/token",
:authorize_url => "/o/oauth2/auth")
end
def authorize
auth_url = client.auth_code.authorize_url(
:redirect_uri => @redirect_uri,
:scope =>
["https://docs.google.com/feeds/",
"https://docs.googleusercontent.com/",
"https://spreadsheets.google.com/feeds/"].join(" "))
puts "Access in your browser: #{auth_url}"
print "And please input authorization code: "
authorization_code = $stdin.gets
auth_token = client.auth_code.get_token(
authorization_code, :redirect_uri => @redirect_uri)
puts "access token: #{auth_token.token}"
puts "refresh token: #{auth_token.refresh_token}"
token_hash = {
:access_token => auth_token.token,
:refresh_token => auth_token.refresh_token,
:expires_at => auth_token.expires_at,
}
open(@file, 'w'){|f| f.print token_hash.to_json }
puts "write token information in #{@file}"
end
def login
token_hash = JSON.parse(File.read(@file))
access_token = OAuth2::AccessToken.from_hash(client, token_hash.dup)
access_token.refesh! if Time.now.to_i > access_token.expires_at
session = GoogleDrive.login_with_oauth(access_token)
end
if ARGV[0]
session = login
# ... write what you want using google drive session
else
authorize
end
@zealoushacker
Copy link

Line 56 has a typo when calling the refresh! method on access_token.

There's an "r" missing. So the line should read:
access_token.refresh! if Time.now.to_i > access_token.expires_at
vs
access_token.refesh! if Time.now.to_i > access_token.expires_at

@zealoushacker
Copy link

Otherwise 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment