forked from cloudant/python-cloudant
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_client_session.py
More file actions
307 lines (252 loc) · 9.32 KB
/
_client_session.py
File metadata and controls
307 lines (252 loc) · 9.32 KB
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
#!/usr/bin/env python
# Copyright (c) 2015, 2019 IBM Corp. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Module containing client session classes.
"""
import base64
import json
import os
from requests import RequestException, Session
from ._2to3 import bytes_, unicode_, url_join
from ._common_util import response_to_json_dict
from .error import CloudantException
class ClientSession(Session):
"""
This class extends Session and provides a default timeout.
"""
def __init__(self, username=None, password=None, session_url=None, **kwargs):
super(ClientSession, self).__init__()
self._username = username
self._password = password
self._session_url = session_url
self._auto_renew = kwargs.get('auto_renew', False)
self._timeout = kwargs.get('timeout', None)
def base64_user_pass(self):
"""
Composes a basic http auth string, suitable for use with the
_replicator database, and other places that need it.
:returns: Basic http authentication string
"""
if self._username is None or self._password is None:
return None
hash_ = base64.urlsafe_b64encode(bytes_("{username}:{password}".format(
username=self._username,
password=self._password
)))
return "Basic {0}".format(unicode_(hash_))
# pylint: disable=arguments-differ
def request(self, method, url, **kwargs):
"""
Overrides ``requests.Session.request`` to set the timeout.
"""
resp = super(ClientSession, self).request(
method, url, timeout=self._timeout, **kwargs)
return resp
def info(self):
"""
Get session information.
"""
if self._session_url is None:
return None
resp = self.get(self._session_url)
resp.raise_for_status()
return response_to_json_dict(resp)
def set_credentials(self, username, password):
"""
Set a new username and password.
:param str username: New username.
:param str password: New password.
"""
if username is not None:
self._username = username
if password is not None:
self._password = password
def login(self):
"""
No-op method - not implemented here.
"""
# pylint: disable=unnecessary-pass
pass
def logout(self):
"""
No-op method - not implemented here.
"""
# pylint: disable=unnecessary-pass
pass
class BasicSession(ClientSession):
"""
This class extends ClientSession to provide basic access authentication.
"""
def __init__(self, username, password, server_url, **kwargs):
super(BasicSession, self).__init__(
username=username,
password=password,
session_url=url_join(server_url, '_session'),
**kwargs)
def request(self, method, url, **kwargs):
"""
Overrides ``requests.Session.request`` to provide basic access
authentication.
"""
auth = None
if self._username is not None and self._password is not None:
auth = (self._username, self._password)
return super(BasicSession, self).request(
method, url, auth=auth, **kwargs)
class CookieSession(ClientSession):
"""
This class extends ClientSession and provides cookie authentication.
"""
def __init__(self, username, password, server_url, **kwargs):
super(CookieSession, self).__init__(
username=username,
password=password,
session_url=url_join(server_url, '_session'),
**kwargs)
def login(self):
"""
Perform cookie based user login.
"""
resp = super(CookieSession, self).request(
'POST',
self._session_url,
data={'name': self._username, 'password': self._password},
auth=(self._username, self._password)
)
resp.raise_for_status()
def logout(self):
"""
Logout cookie based user.
"""
resp = super(CookieSession, self).request(
'DELETE',
self._session_url,
data={'name': self._username, 'password': self._password},
auth=(self._username, self._password)
)
resp.raise_for_status()
def request(self, method, url, **kwargs):
"""
Overrides ``requests.Session.request`` to renew the cookie and then
retry the original request (if required).
"""
resp = super(CookieSession, self).request(method, url, **kwargs)
if not self._auto_renew:
return resp
is_expired = any((
resp.status_code == 403 and
response_to_json_dict(resp).get('error') == 'credentials_expired',
resp.status_code == 401
))
if is_expired:
self.login()
resp = super(CookieSession, self).request(method, url, **kwargs)
return resp
class IAMSession(ClientSession):
"""
This class extends ClientSession and provides IAM authentication.
"""
def __init__(self, api_key, server_url, client_id=None, client_secret=None,
**kwargs):
super(IAMSession, self).__init__(
session_url=url_join(server_url, '_iam_session'),
**kwargs)
self._api_key = api_key
self._token_url = os.environ.get(
'IAM_TOKEN_URL', 'https://iam.cloud.ibm.com/identity/token')
self._token_auth = None
if client_id and client_secret:
self._token_auth = (client_id, client_secret)
@property
def get_api_key(self):
"""
Get IAM API key.
:return: IAM API key.
"""
return self._api_key
def login(self):
"""
Perform IAM cookie based user login.
"""
access_token = self._get_access_token()
try:
super(IAMSession, self).request(
'POST',
self._session_url,
headers={'Content-Type': 'application/json'},
data=json.dumps({'access_token': access_token})
).raise_for_status()
except RequestException:
raise CloudantException(
'Failed to exchange IAM token with Cloudant')
def logout(self):
"""
Logout IAM cookie based user.
"""
self.cookies.clear()
def request(self, method, url, **kwargs):
"""
Overrides ``requests.Session.request`` to renew the IAM cookie
and then retry the original request (if required).
"""
# The CookieJar API prevents callers from getting an individual Cookie
# object by name.
# We are forced to use the only exposed method of discarding expired
# cookies from the CookieJar. Internally this involves iterating over
# the entire CookieJar and calling `.is_expired()` on each Cookie
# object.
self.cookies.clear_expired_cookies()
if self._auto_renew and 'IAMSession' not in self.cookies.keys():
self.login()
resp = super(IAMSession, self).request(method, url, **kwargs)
if not self._auto_renew:
return resp
if resp.status_code == 401:
self.login()
resp = super(IAMSession, self).request(method, url, **kwargs)
return resp
# pylint: disable=arguments-differ, unused-argument
def set_credentials(self, username, api_key):
"""
Set a new IAM API key.
:param str username: Username parameter is unused.
:param str api_key: New IAM API key.
"""
if api_key is not None:
self._api_key = api_key
def _get_access_token(self):
"""
Get IAM access token using API key.
"""
err = 'Failed to contact IAM token service'
try:
resp = super(IAMSession, self).request(
'POST',
self._token_url,
auth=self._token_auth,
headers={'Accepts': 'application/json'},
data={
'grant_type': 'urn:ibm:params:oauth:grant-type:apikey',
'response_type': 'cloud_iam',
'apikey': self._api_key
}
)
err = response_to_json_dict(resp).get('errorMessage', err)
resp.raise_for_status()
return response_to_json_dict(resp)['access_token']
except KeyError:
raise CloudantException('Invalid response from IAM token service')
except RequestException:
raise CloudantException(err)