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.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 @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?
70 # refresh credentials and save them to store
71 def refresh_authorization
72 @authorization.refresh!
73 self.write_credentials
79 # Attempt to read in credentials from the specified store.
81 store.load_credentials
85 # @return [Hash] with credentials
88 :access_token => @authorization.access_token,
89 :authorization_uri => AUTHORIZATION_URI,
90 :client_id => @authorization.client_id,
91 :client_secret => @authorization.client_secret,
92 :expires_in => @authorization.expires_in,
93 :refresh_token => @authorization.refresh_token,
94 :token_credential_uri => TOKEN_CREDENTIAL_URI,
95 :issued_at => @authorization.issued_at.to_i