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
44 # Write the credentials to the specified store.
46 # @params [Signet::OAuth2::Client] authorization
47 # Optional authorization instance. If not provided, the authorization
48 # already associated with this instance will be written.
49 def write_credentials(authorization=nil)
50 @authorization = authorization if authorization
51 if @authorization.respond_to?(:refresh_token) && @authorization.refresh_token
52 store.write_credentials(credentials_hash)
57 # Loads credentials and authorizes an client.
58 # @return [Object] Signet::OAuth2::Client or NIL
61 cached_credentials = load_credentials
62 if cached_credentials && cached_credentials.size > 0
63 @authorization = Signet::OAuth2::Client.new(cached_credentials)
64 @authorization.issued_at = Time.at(cached_credentials['issued_at'].to_i)
65 self.refresh_authorization if @authorization.expired?
71 # refresh credentials and save them to store
72 def refresh_authorization
73 authorization.refresh!
74 self.write_credentials
80 # Attempt to read in credentials from the specified store.
82 store.load_credentials
86 # @return [Hash] with credentials
89 :access_token => authorization.access_token,
90 :authorization_uri => AUTHORIZATION_URI,
91 :client_id => authorization.client_id,
92 :client_secret => authorization.client_secret,
93 :expires_in => authorization.expires_in,
94 :refresh_token => authorization.refresh_token,
95 :token_credential_uri => TOKEN_CREDENTIAL_URI,
96 :issued_at => authorization.issued_at.to_i