1 # Copyright 2013 Google Inc.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 require 'signet/oauth_2/client'
20 # Represents cached OAuth 2 tokens stored on local disk in a
21 # JSON serialized file. Meant to resemble the serialized format
22 # http://google-api-python-client.googlecode.com/hg/docs/epy/oauth2client.file.Storage-class.html
26 AUTHORIZATION_URI = 'https://accounts.google.com/o/oauth2/auth'
27 TOKEN_CREDENTIAL_URI = 'https://accounts.google.com/o/oauth2/token'
29 # @return [Object] Storage object.
32 # @return [Signet::OAuth2::Client]
33 attr_reader :authorization
36 # Initializes the Storage object.
38 # @params [Object] Storage object
45 # Write the credentials to the specified store.
47 # @params [Signet::OAuth2::Client] authorization
48 # Optional authorization instance. If not provided, the authorization
49 # already associated with this instance will be written.
50 def write_credentials(authorization=nil)
51 @authorization = authorization if authorization
52 if @authorization.respond_to?(:refresh_token) && @authorization.refresh_token
53 store.write_credentials(credentials_hash)
58 # Loads credentials and authorizes an client.
59 # @return [Object] Signet::OAuth2::Client or NIL
62 cached_credentials = load_credentials
63 if cached_credentials && cached_credentials.size > 0
64 @authorization = Signet::OAuth2::Client.new(cached_credentials)
65 @authorization.issued_at = Time.at(cached_credentials['issued_at'].to_i)
66 self.refresh_authorization if @authorization.expired?
72 # refresh credentials and save them to store
73 def refresh_authorization
74 authorization.refresh!
75 self.write_credentials
81 # Attempt to read in credentials from the specified store.
83 store.load_credentials
87 # @return [Hash] with credentials
90 :access_token => authorization.access_token,
91 :authorization_uri => AUTHORIZATION_URI,
92 :client_id => authorization.client_id,
93 :client_secret => authorization.client_secret,
94 :expires_in => authorization.expires_in,
95 :refresh_token => authorization.refresh_token,
96 :token_credential_uri => TOKEN_CREDENTIAL_URI,
97 :issued_at => authorization.issued_at.to_i