-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathcache.py
286 lines (226 loc) · 8.58 KB
/
cache.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
"""Caching implementations for reading and writing user credentials."""
import errno
import json
import logging
import os
import os.path
import google.oauth2.credentials
from google.oauth2 import service_account
logger = logging.getLogger(__name__)
_DIRNAME = "pydata"
_FILENAME = "pydata_google_credentials.json"
def _get_default_credentials_path(credentials_dirname, credentials_filename):
"""
Gets the default path to the Google user credentials
Returns
-------
str
Path to the Google user credentials
"""
config_path = None
if os.name == "nt":
config_path = os.getenv("APPDATA")
if not config_path:
config_path = os.path.join(os.path.expanduser("~"), ".config")
config_path = os.path.join(config_path, credentials_dirname)
return os.path.join(config_path, credentials_filename)
def _load_user_credentials_from_info(credentials_json):
credentials = google.oauth2.credentials.Credentials(
token=credentials_json.get("access_token"),
refresh_token=credentials_json.get("refresh_token"),
id_token=credentials_json.get("id_token"),
token_uri=credentials_json.get("token_uri"),
client_id=credentials_json.get("client_id"),
client_secret=credentials_json.get("client_secret"),
scopes=credentials_json.get("scopes"),
)
if credentials and not credentials.valid:
request = google.auth.transport.requests.Request()
try:
credentials.refresh(request)
except google.auth.exceptions.RefreshError:
# Credentials could be expired or revoked. Try to reauthorize.
return None
return credentials
def _load_user_credentials_from_file(credentials_path):
"""
Loads user account credentials from a local file.
Parameters
----------
None
Returns
-------
- GoogleCredentials,
If the credentials can loaded. The retrieved credentials should
also have access to the project (project_id) on BigQuery.
- OR None,
If credentials can not be loaded from a file. Or, the retrieved
credentials do not have access to the project (project_id)
on BigQuery.
"""
try:
with open(credentials_path) as credentials_file:
credentials_json = json.load(credentials_file)
except (IOError, ValueError) as exc:
logger.debug(
"Error loading credentials from {}: {}".format(credentials_path, str(exc))
)
return None
return _load_user_credentials_from_info(credentials_json)
def _save_user_account_credentials(credentials, credentials_path):
"""
Saves user account credentials to a local file.
"""
# Create the direcory if it doesn't exist.
# https://stackoverflow.com/a/12517490/101923
config_dir = os.path.dirname(credentials_path)
if not os.path.exists(config_dir):
try:
os.makedirs(config_dir)
except OSError as exc: # Guard against race condition.
if exc.errno != errno.EEXIST:
logger.warning("Unable to create credentials directory.")
return
try:
with open(credentials_path, "w") as credentials_file:
credentials_json = {
"refresh_token": credentials.refresh_token,
"id_token": credentials.id_token,
"token_uri": credentials.token_uri,
"client_id": credentials.client_id,
"client_secret": credentials.client_secret,
"scopes": credentials.scopes,
# Required for Application Default Credentials to detect the
# credentials type. See:
# https://github.com/pydata/pydata-google-auth/issues/22
"type": "authorized_user",
}
json.dump(credentials_json, credentials_file)
except IOError:
logger.warning("Unable to save credentials.")
def _load_service_account_credentials_from_file(credentials_path, **kwargs):
try:
with open(credentials_path) as credentials_file:
credentials_json = json.load(credentials_file)
except (IOError, ValueError) as exc:
logger.debug(
"Error loading credentials from {}: {}".format(credentials_path, str(exc))
)
return None
return _load_service_account_credentials_from_info(credentials_json, **kwargs)
def _load_service_account_credentials_from_info(credentials_json, **kwargs):
credentials = service_account.Credentials.from_service_account_info(
credentials_json, **kwargs
)
if not credentials.valid:
request = google.auth.transport.requests.Request()
try:
credentials.refresh(request)
except google.auth.exceptions.RefreshError as exc:
# Credentials could be expired or revoked.
logger.debug("Error refreshing credentials: {}".format(str(exc)))
return None
return credentials
class CredentialsCache(object):
"""
Shared base class for crentials classes.
This class also functions as a noop implementation of a credentials class.
"""
def load(self):
"""
Load credentials from disk.
Does nothing in this base class.
Returns
-------
google.oauth2.credentials.Credentials, optional
Returns user account credentials loaded from disk or ``None`` if no
credentials could be found.
"""
pass
def save(self, credentials):
"""
Write credentials to disk.
Does nothing in this base class.
Parameters
----------
credentials : google.oauth2.credentials.Credentials
User credentials to save to disk.
"""
pass
class ReadWriteCredentialsCache(CredentialsCache):
"""
A :class:`~pydata_google_auth.cache.CredentialsCache` which writes to
disk and reads cached credentials from disk.
Parameters
----------
dirname : str, optional
Name of directory to write credentials to. This directory is created
within the ``.config`` subdirectory of the ``HOME`` (``APPDATA`` on
Windows) directory.
filename : str, optional
Name of the credentials file within the credentials directory.
"""
def __init__(self, dirname=_DIRNAME, filename=_FILENAME):
super(ReadWriteCredentialsCache, self).__init__()
self._path = _get_default_credentials_path(dirname, filename)
def load(self):
"""
Load credentials from disk.
Returns
-------
google.oauth2.credentials.Credentials, optional
Returns user account credentials loaded from disk or ``None`` if no
credentials could be found.
"""
return _load_user_credentials_from_file(self._path)
def save(self, credentials):
"""
Write credentials to disk.
Parameters
----------
credentials : google.oauth2.credentials.Credentials
User credentials to save to disk.
"""
_save_user_account_credentials(credentials, self._path)
class WriteOnlyCredentialsCache(CredentialsCache):
"""
A :class:`~pydata_google_auth.cache.CredentialsCache` which writes to
disk, but doesn't read from disk.
Use this class to reauthorize against Google APIs and cache your
credentials for later.
Parameters
----------
dirname : str, optional
Name of directory to write credentials to. This directory is created
within the ``.config`` subdirectory of the ``HOME`` (``APPDATA`` on
Windows) directory.
filename : str, optional
Name of the credentials file within the credentials directory.
"""
def __init__(self, dirname=_DIRNAME, filename=_FILENAME):
super(WriteOnlyCredentialsCache, self).__init__()
self._path = _get_default_credentials_path(dirname, filename)
def save(self, credentials):
"""
Write credentials to disk.
Parameters
----------
credentials : google.oauth2.credentials.Credentials
User credentials to save to disk.
"""
_save_user_account_credentials(credentials, self._path)
NOOP = CredentialsCache()
"""
Noop impmentation of credentials cache.
This cache always reauthorizes and never save credentials to disk.
Recommended for shared machines.
"""
READ_WRITE = ReadWriteCredentialsCache()
"""
Write credentials to disk and read cached credentials from disk.
"""
REAUTH = WriteOnlyCredentialsCache()
"""
Write credentials to disk. Never read cached credentials from disk.
Use this to reauthenticate and refresh the cached credentials.
"""