Skip to content

Instantly share code, notes, and snippets.

@gastonsoto
Forked from Overbryd/0_usage.md
Created November 14, 2015 03:39
Show Gist options
  • Save gastonsoto/55b2af8c024d97e3da06 to your computer and use it in GitHub Desktop.
Save gastonsoto/55b2af8c024d97e3da06 to your computer and use it in GitHub Desktop.
Auto-refreshing XOAuth token system for Google

Usage

Simple as XOauthSession.access_token.

First time usage, either create a yaml file yourself or:

Setup your app at Google developer console. There you follow the menu "APIs & auth" > "Credentials". Click "Create new Client ID" and select "Installed Application" and then "Other". Download oauth2.py and execute the following with the credentials of the Google Developer console.

python oauth2.py --generate_oauth2_token --client_id=<client_id> --client_secret=<client_secret>

Follow its instructions and use the tokens there to create your initial yaml file.

require "xoauth_session"
XOauthSession.new("client_id", "client_secret", "refresh_token", nil, nil).save

This will create a file like the following:

--- !ruby/struct:XOAuthSession
client_id: <client_id>
client_secret: <client_secret>
refresh_token: <refresh_token>
access_token: <access_token>
expires_at: 2015-06-03 20:21:29.350315000 +02:00
require "httparty"
require "yaml"
class XOAuthSession < Struct.new(:client_id, :client_secret, :refresh_token, :access_token, :expires_at)
def self.access_token
load.access_token
end
def self.load
YAML.load_file("xoauth_session.yml")
end
def save
File.open("xoauth_session.yml", "w") { |f| f.write(to_yaml) }
end
def access_token
refresh_access_token if super.nil? || Time.now.to_i >= expires_at.to_i
super
end
def refresh_access_token
response = HTTParty.post("https://accounts.google.com/o/oauth2/token",
body: {
client_id: client_id,
client_secret: client_secret,
refresh_token: refresh_token,
grant_type: "refresh_token"
},
headers: {
"Content-Type" => "application/x-www-form-urlencoded"
}
)
raise "Error Response: #{response.code}" if response.code != 200
self.expires_at = Time.now + response.parsed_response["expires_in"].to_i
self.access_token = response.parsed_response["access_token"]
save
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment