blob: da666c47b52dc914382d795136a085d800e64c2a [file] [log] [blame]
Joe Gregorio20a5aa92011-04-01 17:44:25 -04001# Copyright (C) 2010 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.
Joe Gregorio695fdc12011-01-16 16:46:55 -050014
15"""Utilities for OAuth.
16
17Utilities for making it easier to work with OAuth 2.0
18credentials.
19"""
20
21__author__ = 'jcgregorio@google.com (Joe Gregorio)'
22
23import pickle
Joe Gregorio560b5322011-02-22 11:09:24 -050024import threading
Joe Gregorio695fdc12011-01-16 16:46:55 -050025
Joe Gregoriodeeb0202011-02-15 14:49:57 -050026from client import Storage as BaseStorage
Joe Gregorio695fdc12011-01-16 16:46:55 -050027
Joe Gregoriodeeb0202011-02-15 14:49:57 -050028
29class Storage(BaseStorage):
Joe Gregorio695fdc12011-01-16 16:46:55 -050030 """Store and retrieve a single credential to and from a file."""
31
32 def __init__(self, filename):
Joe Gregorio7c22ab22011-02-16 15:32:39 -050033 self._filename = filename
Joe Gregorio560b5322011-02-22 11:09:24 -050034 self._lock = threading.Lock()
Joe Gregorio695fdc12011-01-16 16:46:55 -050035
36 def get(self):
37 """Retrieve Credential from file.
38
39 Returns:
Joe Gregorio7c22ab22011-02-16 15:32:39 -050040 oauth2client.client.Credentials
Joe Gregorio695fdc12011-01-16 16:46:55 -050041 """
Joe Gregorio560b5322011-02-22 11:09:24 -050042 self._lock.acquire()
Joe Gregoriodeeb0202011-02-15 14:49:57 -050043 try:
Joe Gregorio7c22ab22011-02-16 15:32:39 -050044 f = open(self._filename, 'r')
Joe Gregoriodeeb0202011-02-15 14:49:57 -050045 credentials = pickle.loads(f.read())
46 f.close()
47 credentials.set_store(self.put)
48 except:
49 credentials = None
Joe Gregorio560b5322011-02-22 11:09:24 -050050 self._lock.release()
Joe Gregorio7c22ab22011-02-16 15:32:39 -050051
Joe Gregorio695fdc12011-01-16 16:46:55 -050052 return credentials
53
54 def put(self, credentials):
55 """Write a pickled Credentials to file.
56
57 Args:
58 credentials: Credentials, the credentials to store.
59 """
Joe Gregorio560b5322011-02-22 11:09:24 -050060 self._lock.acquire()
Joe Gregorio7c22ab22011-02-16 15:32:39 -050061 f = open(self._filename, 'w')
Joe Gregorio695fdc12011-01-16 16:46:55 -050062 f.write(pickle.dumps(credentials))
63 f.close()
Joe Gregorio560b5322011-02-22 11:09:24 -050064 self._lock.release()