refactoring load_credentials

adding refresh_authorization

write_credentials now using the authorizations methods not the instance variables, Using the instance variables can cause problems.
This commit is contained in:
Volker Zöpfel 2013-11-14 08:17:08 +01:00
parent 2d326459b2
commit 5538bded1f
1 changed files with 27 additions and 25 deletions

View File

@ -41,18 +41,22 @@ module Google
## ##
# Attempt to read in credentials from the specified file. # Attempt to read in credentials from the specified file.
# TODO: add methods to:
# check if file exists
# check if file is writeable
# check json structure is valid
def load_credentials def load_credentials
if File.exist? self.path cached_credentials = JSON.load(self.path)
File.open(self.path, 'r') do |file| @authorization = Signet::OAuth2::Client.new(cached_credentials)
cached_credentials = JSON.load(file) @authorization.issued_at = Time.at(cached_credentials['issued_at'])
@authorization = Signet::OAuth2::Client.new(cached_credentials) self.refresh_authorization if @authorization.expired?
@authorization.issued_at = Time.at(cached_credentials['issued_at']) end
if @authorization.expired?
@authorization.fetch_access_token! ##
self.write_credentials # refresh credentials and save them to file
end def refresh_authorization
end @authorization.refresh!
end self.write_credentials(@authorization)
end end
## ##
@ -62,23 +66,21 @@ module Google
# Optional authorization instance. If not provided, the authorization # Optional authorization instance. If not provided, the authorization
# already associated with this instance will be written. # already associated with this instance will be written.
def write_credentials(authorization=nil) def write_credentials(authorization=nil)
@authorization = authorization unless authorization.nil? @authorization = authorization if authorization
if @authorization.refresh_token
unless @authorization.refresh_token.nil? credentials_hash = {
hash = {} 'access_token' => @authorization.access_token,
%w'access_token 'authorization_uri' => @authorization.authorization_uri,
authorization_uri 'client_id' => @authorization.client_id,
client_id 'client_secret' => @authorization.client_secret,
client_secret 'expires_in' => @authorization.expires_in,
expires_in 'refresh_token' => @authorization.refresh_token,
refresh_token 'token_credential_uri' => @authorization.token_credential_uri
token_credential_uri'.each do |var| }
hash[var] = @authorization.instance_variable_get("@#{var}")
end
hash['issued_at'] = @authorization.issued_at.to_i
File.open(self.path, 'w', 0600) do |file| File.open(self.path, 'w', 0600) do |file|
file.write(hash.to_json) file.write(credentials_hash.to_json)
end end
end end
end end