wachichornia
wachichornia

Reputation: 1188

How do I save Google API credentials in Ruby?

I feel stupid. I get the authorization code, and am able to access the drive API at the moment, which is what I almost want.

I want to be able to access the API offline, but I still don't understand how am I supposed to save the credentials.

My question is, what am I supposed to put inside this method?

# Store OAuth 2.0 credentials in the application's database.
#
# @param [String] user_id
#   User's ID.
# @param [Signet::OAuth2::Client] credentials
#   OAuth 2.0 credentials to store.
def store_credentials(user_id, credentials)
  raise NotImplementedError, 'store_credentials is not implemented.'
end

So I can later run:

client = Google::APIClient.new
client.authorization = credentials
client = client.discovered_api('drive', 'v2')
client

Without having to ask the user for permission again

Upvotes: 4

Views: 655

Answers (1)

Ich
Ich

Reputation: 1378

You could write it to an file:

def store_credentials(user_id, credentials)
   File.write 'credentials.data', [user_id, credentials].to_json
end

and later read it from that file:

require 'json' 
user_id, credentials = *JSON.parse(File.read('credentials.data'))
client.authorization = credentials

Upvotes: 1

Related Questions