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.
16 require 'signet/oauth_2/client'
21 # Represents cached OAuth 2 tokens stored on local disk in a
22 # JSON serialized file. Meant to resemble the serialized format
23 # http://google-api-python-client.googlecode.com/hg/docs/epy/oauth2client.file.Storage-class.html
26 # @return [String] Path to the credentials file.
29 # @return [Signet::OAuth2::Client] Path to the credentials file.
30 attr_reader :authorization
33 # Initializes the FileStorage object.
35 # @param [String] path
36 # Path to the credentials file.
43 # Attempt to read in credentials from the specified file.
45 if File.exists? self.path
46 File.open(self.path, 'r') do |file|
47 cached_credentials = JSON.load(file)
48 @authorization = Signet::OAuth2::Client.new(cached_credentials)
49 @authorization.issued_at = Time.at(cached_credentials['issued_at'])
50 if @authorization.expired?
51 @authorization.fetch_access_token!
52 self.write_credentials
59 # Write the credentials to the specified file.
61 # @param [Signet::OAuth2::Client] authorization
62 # Optional authorization instance. If not provided, the authorization
63 # already associated with this instance will be written.
64 def write_credentials(authorization=nil)
65 @authorization = authorization unless authorization.nil?
67 unless @authorization.refresh_token.nil?
75 token_credential_uri'.each do |var|
76 hash[var] = @authorization.instance_variable_get("@#{var}")
78 hash['issued_at'] = @authorization.issued_at.to_i
80 File.open(self.path, 'w', 0600) do |file|
81 file.write(hash.to_json)