def _refresh(self, http_request): """Refreshes the access_token. Skip all the storage hoops and just refresh using the API. Args: http_request: callable, a callable that matches the method signature of httplib2.Http.request, used to make the refresh request. Raises: AccessTokenRefreshError: When the refresh fails. """ query = '?scope=%s' % urllib.parse.quote(self.scope, '') uri = META.replace('{?scope}', query) response, content = http_request(uri) if response.status == 200: try: d = json.loads(content) except Exception as e: raise AccessTokenRefreshError(str(e)) self.access_token = d['accessToken'] else: if response.status == 404: content += (' This can occur if a VM was created' ' with no service account or scopes.') raise AccessTokenRefreshError(content)
def testCreateHttpHeader_refreshFails(self): self.mock_oauth2_credentials.refresh.side_effect = AccessTokenRefreshError( 'Invalid response 400') with mock.patch('httplib2.Http', self.http): self.assertRaises(AccessTokenRefreshError, self.googleads_client.CreateHttpHeader) self.assertFalse(self.mock_oauth2_credentials.apply.called)
def _refresh(self, http_request): """Refreshes the access_token. Skip all the storage hoops and just refresh using the API. Args: http_request: callable, a callable that matches the method signature of httplib2.Http.request, used to make the refresh request. Raises: AccessTokenRefreshError: When the refresh fails. """ uri = uritemplate.expand(META, {'scope': self.scope}) response, content = http_request(uri) if response.status == 200: try: d = simplejson.loads(content) except Exception as e: raise AccessTokenRefreshError(str(e)) self.access_token = d['accessToken'] else: raise AccessTokenRefreshError(content)
def _service(self, http=None): if not (http or self._oauth2token or self._decorator): raise GoogleSpreadsheetsError('please set oauth2 credentials' ' or oauth2 decorator') if http: token = OAuth2BearerToken(http.request.credentials) elif self._decorator: token = OAuth2BearerToken(self._decorator.credentials) else: token = self._oauth2token try: return SpreadsheetsClient(auth_token=token) except Unauthorized as e: raise AccessTokenRefreshError(e.message)
def testExceptionHandlerAccessTokenErrorRaises(self): exception_arg = AccessTokenRefreshError() retry_args = http_wrapper.ExceptionRetryArgs( http={'connections': {}}, http_request=_MockHttpRequest(), exc=exception_arg, num_retries=0, max_retry_wait=0, total_wait_sec=0) # Disable time.sleep for this handler as it is called with # a minimum value of 1 second. with self.assertRaises(AccessTokenRefreshError): with patch('time.sleep', return_value=None): http_wrapper.HandleExceptionsAndRebuildHttpConnections( retry_args)
def _refresh(self, http_request): """Refreshes the access_token. Since the underlying App Engine app_identity implementation does its own caching we can skip all the storage hoops and just to a refresh using the API. Args: http_request: callable, a callable that matches the method signature of httplib2.Http.request, used to make the refresh request. Raises: AccessTokenRefreshError: When the refresh fails. """ try: (token, _) = app_identity.get_access_token(self.scope) except app_identity.Error, e: raise AccessTokenRefreshError(str(e))
def test_required(self): # An initial request to an oauth_required decorated path should be a # redirect to start the OAuth dance. self.assertEqual(self.decorator.flow, None) self.assertEqual(self.decorator.credentials, None) response = self.app.get('http://localhost/foo_path') self.assertTrue(response.status.startswith('302')) q = urllib.parse.parse_qs(response.headers['Location'].split('?', 1)[1]) self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0]) self.assertEqual('foo_client_id', q['client_id'][0]) self.assertEqual('foo_scope bar_scope', q['scope'][0]) self.assertEqual('http://localhost/foo_path', q['state'][0].rsplit(':', 1)[0]) self.assertEqual('code', q['response_type'][0]) self.assertEqual(False, self.decorator.has_credentials()) with mock.patch.object(appengine, '_parse_state_value', return_value='foo_path', autospec=True) as parse_state_value: # Now simulate the callback to /oauth2callback. response = self.app.get('/oauth2callback', { 'code': 'foo_access_code', 'state': 'foo_path:xsrfkey123', }) parts = response.headers['Location'].split('?', 1) self.assertEqual('http://localhost/foo_path', parts[0]) self.assertEqual(None, self.decorator.credentials) if self.decorator._token_response_param: response_query = urllib.parse.parse_qs(parts[1]) response = response_query[ self.decorator._token_response_param][0] self.assertEqual(Http2Mock.content, json.loads(urllib.parse.unquote(response))) self.assertEqual(self.decorator.flow, self.decorator._tls.flow) self.assertEqual(self.decorator.credentials, self.decorator._tls.credentials) parse_state_value.assert_called_once_with('foo_path:xsrfkey123', self.current_user) # Now requesting the decorated path should work. response = self.app.get('/foo_path') self.assertEqual('200 OK', response.status) self.assertEqual(True, self.had_credentials) self.assertEqual('foo_refresh_token', self.found_credentials.refresh_token) self.assertEqual('foo_access_token', self.found_credentials.access_token) self.assertEqual(None, self.decorator.credentials) # Raising an exception still clears the Credentials. self.should_raise = Exception('') self.assertRaises(Exception, self.app.get, '/foo_path') self.should_raise = False self.assertEqual(None, self.decorator.credentials) # Access token refresh error should start the dance again self.should_raise = AccessTokenRefreshError() response = self.app.get('/foo_path') self.should_raise = False self.assertTrue(response.status.startswith('302')) query_params = urllib.parse.parse_qs( response.headers['Location'].split('?', 1)[1]) self.assertEqual('http://localhost/oauth2callback', query_params['redirect_uri'][0]) # Invalidate the stored Credentials. self.found_credentials.invalid = True self.found_credentials.store.put(self.found_credentials) # Invalid Credentials should start the OAuth dance again. response = self.app.get('/foo_path') self.assertTrue(response.status.startswith('302')) query_params = urllib.parse.parse_qs( response.headers['Location'].split('?', 1)[1]) self.assertEqual('http://localhost/oauth2callback', query_params['redirect_uri'][0])
"""Refreshes the access_token. Skip all the storage hoops and just refresh using the API. Args: http_request: callable, a callable that matches the method signature of httplib2.Http.request, used to make the refresh request. Raises: AccessTokenRefreshError: When the refresh fails. """ uri = uritemplate.expand(META, {'scope': self.scope}) response, content = http_request(uri) if response.status == 200: try: d = simplejson.loads(content) except StandardError, e: raise AccessTokenRefreshError(str(e)) self.access_token = d['accessToken'] else: if response.status == 404: content = content + (' This can occur if a VM was created' ' with no service account or scopes.') raise AccessTokenRefreshError(content) def create_scoped_required(self): return not self.scope def create_scoped(self, scopes): return AppAssertionCredentials(scopes, **self.kwargs)
def raise_invalid_grant(*args, **kwargs): raise AccessTokenRefreshError()
def test_email有問題(self, authorizeMocka): authorizeMocka.side_effect = AccessTokenRefreshError() with io.StringIO() as 輸出: call_command('顯示全部sheet狀態', stdout=輸出) self.assertIn('email有問題', 輸出.getvalue())