Created
October 2, 2012 09:38
-
-
Save holysugar/3817860 to your computer and use it in GitHub Desktop.
google-drive-ruby with oauth sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line 56 has a typo when calling the
refresh!
method onaccess_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