get token, store it, refresh it if expired using oauth2 gem in ruby

ben picture ben · Oct 23, 2014 · Viewed 8.2k times · Source

I am working on script to get google contacts using google contacts api gem. I am able to access the token successfully using this code:

require 'rubygems'
require 'launchy'
require 'oauth2'
require 'googlecontacts'
require 'google_contacts_api'

# Get your credentials from the console
CLIENT_ID = 'your Id'
CLIENT_SECRET = 'your Secret'
OAUTH_SCOPE = 'https://www.google.com/m8/feeds'
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'

client = OAuth2::Client.new(CLIENT_ID, CLIENT_SECRET,site: 'https://accounts.google.com',token_url: '/o/oauth2/token', authorize_url: '/o/oauth2/auth')
url = client.auth_code.authorize_url(scope: OAUTH_SCOPE, redirect_uri: REDIRECT_URI)
Launchy.open(url)
$stdout.write  "Enter authorization code: "
code = gets.chomp
token = client.auth_code.get_token(code, :redirect_uri => REDIRECT_URI)

PROBLEM:

I know that this is not the best way to do it, because it is tiring. every time I run the script the user has give access instructions. And also I have to manually copy paste the token from the browser to the terminal.

QUESTION:

How can be able to store the retrieved token, and when it expired how can I refresh it?

Answer

Eric Koleda picture Eric Koleda · Oct 23, 2014

It looks like you're using the oauth2 library to get the access token. The AccessToken class has to_hash() and from_hash() methods, which you can use to serialize and deserialize the token once you've gotten it, as well as a refresh() method to refresh the access token once it's expired. If this is a command line script you can use a hidden file in the user's home directory to store the serialized token.