Created
March 15, 2013 12:25
-
-
Save mahemoff/5169541 to your computer and use it in GitHub Desktop.
This file contains 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
def fresh_access_token | |
client = OAuth2::Client.new(strategy[:client_id], strategy[:client_secret]) | |
OAuth2::AccessToken.new client, fresh_token_record.token | |
end | |
def fresh_token_record(tries_remaining=1) | |
token_record = load_token_record | |
need_a_fresh_access_token = !token_record.expires_at or (DateTime.now > token_record.expires_at - 1.minute) | |
puts 'need new token ?', need_a_fresh_access_token | |
return token_record unless need_a_fresh_access_token | |
# see http://stackoverflow.com/a/12574402/18706 | |
data = { | |
:client_id => strategy[:client_id], | |
:client_secret => strategy[:client_secret], | |
:refresh_token => token_record.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? | |
token_record.update_attributes( | |
token: @response["access_token"], | |
expires_at: DateTime.now + @response["expires_in"].seconds - 10.seconds # expires_in should normally be 3600 | |
) | |
token_record | |
else | |
logger.info "No token exchanged for user token #{token_record.inspect}" | |
end | |
rescue => e | |
logger.error "Could not call to exchange token, or had a problem receiving it. #{token_record.inspect}. Error Was:\n {e.inspect}" | |
nil | |
end | |
def verified_token | |
get "https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=#{fresh_token_record.token}" | |
end | |
def get(url) | |
puts "GET", url | |
response = fresh_access_token.get url | |
end | |
def get_json(url) | |
Hashie::Mash.new(JSON.parse get(url).response.body) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment