Skip to content
This repository was archived by the owner on Aug 30, 2024. It is now read-only.

Commit 59ca68f

Browse files
committed
Renew IAM token on 401 status code or cookie expiry
1 parent 275057a commit 59ca68f

File tree

2 files changed

+5
-30
lines changed

2 files changed

+5
-30
lines changed

src/cloudant/_common_util.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -425,18 +425,16 @@ def request(self, method, url, **kwargs): # pylint: disable=W0221
425425
Overrides ``requests.Session.request`` to renew the IAM cookie
426426
and then retry the original request (if required).
427427
"""
428+
self.cookies.clear_expired_cookies()
429+
if self._auto_renew and 'IAMSession' not in self.cookies.keys():
430+
self.login()
431+
428432
resp = super(IAMSession, self).request(method, url, **kwargs)
429433

430434
if not self._auto_renew or url in [self._session_url, self._token_url]:
431435
return resp
432436

433-
is_expired = any((
434-
resp.status_code == 403 and
435-
resp.json().get('error') == 'credentials_expired',
436-
resp.status_code == 401
437-
))
438-
439-
if is_expired:
437+
if resp.status_code == 401:
440438
self.login()
441439
resp = super(IAMSession, self).request(method, url, **kwargs)
442440

tests/unit/iam_auth_tests.py

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -234,29 +234,6 @@ def test_iam_renew_cookie_on_401_success(self, m_req, m_login):
234234
self.assertEqual(m_login.call_count, 2)
235235
self.assertEqual(m_req.call_count, 3)
236236

237-
238-
@mock.patch('cloudant._common_util.IAMSession.login')
239-
@mock.patch('cloudant._common_util.ClientSession.request')
240-
def test_iam_renew_cookie_on_403(self, m_req, m_login):
241-
# mock 200
242-
m_response_ok = mock.MagicMock()
243-
type(m_response_ok).status_code = mock.PropertyMock(return_value=200)
244-
m_response_ok.json.return_value = {'ok': True}
245-
# mock 403
246-
m_response_bad = mock.MagicMock()
247-
type(m_response_bad).status_code = mock.PropertyMock(return_value=403)
248-
m_response_bad.json.return_value = {'error': 'credentials_expired'}
249-
250-
m_req.side_effect = [m_response_bad, m_response_ok]
251-
252-
iam = IAMSession('foo', 'http://127.0.0.1:5984', auto_renew=True)
253-
iam.login()
254-
255-
resp = iam.request('GET', 'http://127.0.0.1:5984/mydb1')
256-
257-
self.assertEqual(m_login.call_count, 2)
258-
self.assertTrue(resp.json()['ok'])
259-
260237
@mock.patch('cloudant._common_util.IAMSession.login')
261238
@mock.patch('cloudant._common_util.ClientSession.request')
262239
def test_iam_renew_cookie_on_401_failure(self, m_req, m_login):

0 commit comments

Comments
 (0)