use authorization method instead of variable
[arvados.git] / lib / google / api_client / auth / storages / file_store.rb
1 # Copyright 2013 Google Inc.
2 #
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
6 #
7 #      http://www.apache.org/licenses/LICENSE-2.0
8 #
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.
14
15 require 'json'
16
17 module Google
18   class APIClient
19     ##
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
23     #
24     class FileStore
25
26       attr_accessor :path
27
28       ##
29       # Initializes the FileStorage object.
30       #
31       # @param [String] path
32       #    Path to the credentials file.
33       def initialize(path)
34         @path= path
35       end
36
37       ##
38       # Attempt to read in credentials from the specified file.
39       def load_credentials
40         if File.exists?(path) && File.readable?(path) && File.writable?(path)
41           credentials = File.open(path, 'r') { |f| JSON.parse(f.read) }
42         end
43         credentials
44       end
45
46       ##
47       # Write the credentials to the specified file.
48       #
49       # @param [Signet::OAuth2::Client] authorization
50       #    Optional authorization instance. If not provided, the authorization
51       #    already associated with this instance will be written.
52       def write_credentials(credentials_hash)
53         File.open(self.path, 'w') do |file|
54           file.write(credentials_hash.to_json)
55         end
56       end
57     end
58   end
59 end