def _GetCachedCredentials(self): """Get credentials from cached file or json file. Returns: OAuth2Credentials object. Raises: AuthenticationError on failure to read json file. """ storage = oauth_client_fileio.Storage(self._token_cache_file) # Try loading credentials from existing token cache file. if os.path.isfile(self._token_cache_file): credentials = storage.get() if credentials and not credentials.invalid: return credentials if self._token_json_file is None: raise AuthenticationError('Gmail token file path is not provided.') # Create new credentials if cache file doesn't exist or not valid. refresh_token_json = ReadRefreshTokenJson(self._token_json_file) credentials = client.OAuth2Credentials( access_token=None, client_id=refresh_token_json.client_id, client_secret=refresh_token_json.client_secret, refresh_token=refresh_token_json.refresh_token, token_expiry=None, token_uri=self.TOKEN_URI, user_agent=None, revoke_uri=None) credentials.set_store(storage) storage.put(credentials) return credentials
def FromJson(json_value): """Returns Oauth2client credentials from library independent json format.""" json_key = json.loads(json_value) cred_type = CredentialType.FromTypeKey(json_key['type']) if cred_type == CredentialType.SERVICE_ACCOUNT: cred = service_account.ServiceAccountCredentials.from_json_keyfile_dict( json_key, scopes=config.CLOUDSDK_SCOPES) cred.user_agent = cred._user_agent = config.CLOUDSDK_USER_AGENT elif cred_type == CredentialType.USER_ACCOUNT: cred = client.OAuth2Credentials( access_token=None, client_id=json_key['client_id'], client_secret=json_key['client_secret'], refresh_token=json_key['refresh_token'], token_expiry=None, token_uri=json_key.get('token_uri'), user_agent=json_key.get('user_agent'), revoke_uri=json_key.get('revoke_uri'), id_token=json_key.get('id_token'), token_response=json_key.get('token_response'), scopes=json_key.get('scopes'), token_info_uri=json_key.get('token_info_uri'), rapt_token=json_key.get('rapt_token'), ) elif cred_type == CredentialType.P12_SERVICE_ACCOUNT: # pylint: disable=protected-access cred = service_account.ServiceAccountCredentials._from_p12_keyfile_contents( service_account_email=json_key['client_email'], private_key_pkcs12=base64.b64decode(json_key['private_key']), private_key_password=json_key['password'], scopes=config.CLOUDSDK_SCOPES) cred.user_agent = cred._user_agent = config.CLOUDSDK_USER_AGENT else: raise UnknownCredentialsType(json_key['type']) return cred
def OAuth2Credentials_from_json(self, data): EXPIRY_FORMAT = '%Y-%m-%dT%H:%M:%SZ' if (data.get('token_expiry') and not isinstance(data['token_expiry'], datetime.datetime)): try: data['token_expiry'] = datetime.datetime.strptime( data['token_expiry'], EXPIRY_FORMAT) except ValueError: data['token_expiry'] = None return client.OAuth2Credentials( data['access_token'], data['client_id'], data['client_secret'], data['refresh_token'], data['token_expiry'], data['token_uri'], data['user_agent'], revoke_uri=data.get('revoke_uri', None), id_token=data.get('id_token', None), id_token_jwt=data.get('id_token_jwt', None), token_response=data.get('token_response', None), scopes=data.get('scopes', None), token_info_uri=data.get('token_info_uri', None))
def _google_analytics_credentials_from_user_credentials( client_id: str, client_secret: str, refresh_token: str ): '''Returns the credentials from user authenticated client_id, client_secret, refresh_token See https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py for how to get such credentials including the initial refresh token ''' # https://stackoverflow.com/a/42230541/1380673 import oauth2client import oauth2client.client as client credentials = client.OAuth2Credentials( access_token=None, # set access_token to None since we use a refresh token client_id=client_id, client_secret=client_secret, refresh_token=refresh_token, token_expiry=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, user_agent=None, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, scopes=SCOPES) return credentials
def get_service(request): BASE = os.path.dirname(os.path.abspath(__file__)) client_secret_path = os.path.join(BASE, 'client_secret.json') print client_secret_path client_secret = None with open(client_secret_path) as client_secret_json: client_secret = json.load(client_secret_json) user = request.user token = user.user_token credentials = client.OAuth2Credentials( access_token=token.accessToken, refresh_token=token.refreshToken, token_expiry=token.tokenExpiry, token_uri=client_secret['installed']['token_uri'], client_id=client_secret['installed']['client_id'], client_secret=client_secret['installed']['client_secret'], user_agent=None) http_auth = credentials.authorize(httplib2.Http()) service = discovery.build('calendar', 'v3', http_auth) return service
def get_credentials(self, user_id): with self.conn: result = self.conn.execute( "SELECT access_token, refresh_token from OAuthDetails WHERE google_plus_id=?", (user_id, )) row = result.fetchone() access_token = row[0] refresh_token = row[1] print "tokens", refresh_token http = Http() credentials = AccessTokenCredentials( access_token, "antunovic-calendar-client/1.0") token_info = credentials.get_access_token(http) print "Still okay? ", token_info.expires_in if token_info.expires_in > 60 * 2: return credentials with open("client_secrets.json") as client_secrets_file: data = json.load(client_secrets_file) token_uri = data["web"]["token_uri"] client_id = data["web"]["client_id"] client_secret = data["web"]["client_secret"] google_token_uri = data["web"]["client_id"] return client.OAuth2Credentials(None, client_id, client_secret, refresh_token, None, GOOGLE_TOKEN_URI, None, revoke_uri=GOOGLE_REVOKE_URI)
def SetUp(self): properties.VALUES.core.account.Set('fakeuser') self.fake_cred = client.OAuth2Credentials( 'access-token', 'client_id', 'client_secret', 'fake-token', None, 'token_uri', 'user_agent', scopes=config.CLOUDSDK_SCOPES) store.Store(self.fake_cred) self.refresh_mock = self.StartObjectPatch(client.OAuth2Credentials, 'refresh') self.mock_client = mock.Client( apis.GetClientClass('iamcredentials', 'v1')) self.mock_client.Mock() self.addCleanup(self.mock_client.Unmock) self.messages = self.mock_client.MESSAGES_MODULE self.gen_request_msg = ( self.messages. IamcredentialsProjectsServiceAccountsGenerateAccessTokenRequest) self.request_mock = self.StartObjectPatch(httplib2.Http, 'request', autospec=True)
def test_oauth_tokens_are_updated_on_each_login(self): """ Test that when a user re-authenticates (i.e. logs back in) with our backend, that we update their User object with the new oauth tokens. """ User = get_user_model() mock_userinfo = json.loads(MOCK_GET_PROFILE_RESPONSE) very_future = timezone.now() + timezone.timedelta(days=10) # Create a user who has logged in before, e.g one that has oauth tokens user = AuthenticatedUserFactory.create(email=mock_userinfo['email'], token_expiry=timezone.now() + timezone.timedelta(days=1)) new_credentials = client.OAuth2Credentials( 'my_token', 'my_client_id', 'my_client_secret', 'my_refresh_token', very_future, 'https://example.com/my/token/uri', 'my_user_agent') backend = OauthenticationBackend() with mock.patch('accounts.backends.get_user_info', return_value=mock_userinfo): backend.authenticate(oauth_credentials=new_credentials) # Now check that the User object has been updated with the new creds user = User.objects.get(pk=user.pk) self.assertEqual(user.access_token, new_credentials.access_token) self.assertEqual(user.refresh_token, new_credentials.refresh_token) self.assertEqual(user.token_expiry, new_credentials.token_expiry)
def SetUp(self): self.fake_project = 'fake-project' self.fake_account = 'fake-account' properties.VALUES.core.account.Set(self.fake_account) properties.VALUES.core.project.Set(self.fake_project) # Set up user credentials self.fake_cred = client.OAuth2Credentials( 'access-token', 'client_id', 'client_secret', 'fake-token', datetime.datetime(2021, 1, 8, 0, 0, 0), 'token_uri', 'user_agent', scopes=config.CLOUDSDK_SCOPES) store.Store(self.fake_cred) store.Load() self.api_version = artifacts.API_VERSION_FOR_TRACK[self.track] self.client = mock.Client( core_apis.GetClientClass(API_NAME, self.api_version), real_client=core_apis.GetClientInstance(API_NAME, self.api_version)) self.client.Mock() self.messages = core_apis.GetMessagesModule(API_NAME, self.api_version) self.addCleanup(self.client.Unmock)
def scrape(self, user_data): """ Scrape photos from google photos using the following API: https://developers.google.com/drive/v3/reference/ """ try: oauth = user_data.services['google'] except KeyError: return False if 'denied' in oauth: return False credentials = client.OAuth2Credentials( access_token=oauth['access_token'], client_id=CONFIG.get('google_client_id'), client_secret=CONFIG.get('google_client_secret'), refresh_token=oauth.get('refresh_token', None), token_uri=client.GOOGLE_TOKEN_URI, token_expiry=oauth.get('expires_in', None), user_agent='QS-server-agent/1.0', id_token=oauth.get('id_token', None)) http = credentials.authorize(httplib2.Http()) gplus = build('drive', 'v3', http=http) photos = list( apiclient_paginate(gplus.files(), 'list', { 'spaces': 'photos', 'fields': 'files,kind,nextPageToken', }, max_results=self.num_images_per_user)) for photo in photos: faces = yield find_faces_url(photo['thumbnailLink'], upsample=2) photo['faces'] = faces return photos
def _google_sheet_credentials_from_user_credentials(client_id: str, client_secret: str, refresh_token: str): '''Returns the credentials from user authenticated client_id, client_secret, refresh_token The credentials need to have the scope set to ['https://spreadsheets.google.com/feeds'] See https://developers.google.com/sheets/api/quickstart/python for how to get such credentials including the initial refresh token ''' # https://stackoverflow.com/a/42230541/1380673 import oauth2client import oauth2client.client as client credentials = client.OAuth2Credentials( access_token= None, # set access_token to None since we use a refresh token client_id=client_id, client_secret=client_secret, refresh_token=refresh_token, token_expiry=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, user_agent=None, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, scopes=SCOPES) return credentials
def _get_google_analytics_service_object(self, client_id, client_secret, refresh_token): # Validate authentication keys if not client_id: raise CommandError( 'Missing required setting: GOOGLE_DEVELOPER_CLIENT_ID') if not client_secret: raise CommandError( 'Missing required setting: GOOGLE_DEVELOPER_CLIENT_SECRET') if not refresh_token: raise CommandError( 'Missing required setting: GOOGLE_DEVELOPER_REFRESH_TOKEN') # Create credentials using refresh token credentials = client.OAuth2Credentials(None, client_id, client_secret, refresh_token, None, GOOGLE_TOKEN_URI, None, revoke_uri=GOOGLE_REVOKE_URI, id_token=None, token_response=None) # Create an httplib2.Http object and authorize it with our credentials http = httplib2.Http() http = credentials.authorize(http) # Build the Analytics Service Object with the authorized http object service = build('analytics', 'v3', http=http) return service
def test_cloud_credentials_constructor_no_local_file( self, expected_redirect_uri, run_web_server, mock_run_flow, mock_server_flow): """Test the creation of the CloudCredentials object with no local creds.""" FLAGS.automatic_oauth = run_web_server mock_run_flow.return_value = oauth2_client.OAuth2Credentials( access_token='test_access_token', client_id=self._test_config.client_id, client_secret=self._test_config.client_secret, refresh_token='test_refresh_token', token_expiry=datetime.datetime(year=2018, month=1, day=1), token_uri='test_token_uri', user_agent=None, id_token='test_id_token', scopes=['test_scope1']) test_creds = auth.CloudCredentials(self._test_config, ['test_scope1']) self.assertEqual(self._test_config, test_creds._config) self.assertEqual('test_access_token', test_creds._credentials.token) self.assertEqual( 'test_refresh_token', test_creds._credentials.refresh_token) self.assertEqual('test_id_token', test_creds._credentials.id_token) self.assertEqual('test_token_uri', test_creds._credentials.token_uri) self.assertEqual( self._test_config.client_id, test_creds._credentials.client_id) self.assertEqual( self._test_config.client_secret, test_creds._credentials.client_secret) self.assertEqual(['test_scope1'], test_creds._credentials.scopes) mock_server_flow.assert_called_once_with( client_id=self._test_config.client_id, client_secret=self._test_config.client_secret, scope=['test_scope1'], redirect_uri=expected_redirect_uri)
def _get_credentials(path, client_id=None, client_secret=None): """Retrieve the OAuth2Credentials used for making API requests. This will step through the authentication flow the first time it is called and save credentials to the dbm_sample.yaml file in your home directory. In subsequent runs, it will use the credentials saved to this file automatically unless a different path is specified. Args: path: str path to the file used for storing authentication data. client_id: str containing your client ID. client_secret: str containing your client secret. Returns: An OAuth2Credentials instance. """ try: auth_data = _load_auth_yaml(path) credentials = client.OAuth2Credentials( None, auth_data['client_id'], auth_data['client_secret'], auth_data['refresh_token'], datetime.datetime(1983, 7, 14, 12), _GOOGLE_OAUTH2_ENDPOINT, _USER_AGENT) except IOError: print('Failed to retrieve credentials, stepping through OAuth2 flow.') credentials = _handle_oauth2_flow(client_id, client_secret) _save_auth_yaml(path, credentials) return credentials
class UtilsTests(sdk_test_base.SdkBase, parameterized.TestCase): @parameterized.parameters((True, {}, 'fake_token_host'), (True, { 'token_uri': 'another_token_host' }, 'fake_token_host'), (False, {}, properties.VALUES.auth.DEFAULT_TOKEN_HOST), (False, { 'token_uri': 'another_token_host' }, 'another_token_host')) def testGetEffectiveTokenUri(self, explicitly_set, cred_json, expected_value): if explicitly_set: properties.VALUES.auth.token_host.Set('fake_token_host') self.assertEqual(expected_value, creds.GetEffectiveTokenUri(cred_json)) @parameterized.parameters( (google_auth_credentials.UserCredWithReauth('access_token', 'refresh_token'), True, True), (google_auth_credentials.UserCredWithReauth( 'access_token', 'refresh_token'), False, True), (google_auth_gce.Credentials(), True, True), (google_auth_gce.Credentials(), False, False), (UnKnownCredentials(), True, False), (UnKnownCredentials(), False, False), ) def testIsUserAccountCredentialsGoogleAuth(self, credentials, is_devshell, expected_result): self.StartObjectPatch( devshell, 'IsDevshellEnvironment', return_value=is_devshell) self.assertEqual( creds.IsUserAccountCredentials(credentials), expected_result) @parameterized.parameters( (client.OAuth2Credentials('token', 'client_id', 'client_secret', 'refresh_token', None, None, None), True, True), (client.OAuth2Credentials('token', 'client_id', 'client_secret', 'refresh_token', None, None, None), False, True), (gce.AppAssertionCredentials(), True, True), (gce.AppAssertionCredentials(), False, False), (UnKnownCredentials(), True, False), (UnKnownCredentials(), False, False), ) def testIsUserAccountCredentialsOauth2client(self, credentials, is_devshell, expected_result): self.StartObjectPatch( devshell, 'IsDevshellEnvironment', return_value=is_devshell) self.assertEqual( creds.IsUserAccountCredentials(credentials), expected_result)
def __init__(self, host, refresh_token, user_agent, source, host_override=None, extra_headers=None, save_cookies=False, auth_tries=None, account_type=None, debug_data=True, secure=True, ignore_certs=False, rpc_tries=3): """Creates a new HttpRpcServerOauth2. Args: host: The host to send requests to. refresh_token: A string refresh token to use, or None to guide the user through the auth flow. (Replaces auth_function on parent class.) user_agent: The user-agent string to send to the server. Specify None to omit the user-agent header. source: Tuple, (client_id, client_secret, scope), for oauth credentials. host_override: The host header to send to the server (defaults to host). extra_headers: A dict of extra headers to append to every request. Values supplied here will override other default headers that are supplied. save_cookies: If the refresh token should be saved. auth_tries: The number of times to attempt auth_function before failing. account_type: Ignored. debug_data: Whether debugging output should include data contents. secure: If the requests sent using Send should be sent over HTTPS. ignore_certs: If the certificate mismatches should be ignored. rpc_tries: The number of rpc retries upon http server error (i.e. Response code >= 500 and < 600) before failing. """ super(HttpRpcServerOauth2, self).__init__( host, None, user_agent, None, host_override=host_override, extra_headers=extra_headers, auth_tries=auth_tries, debug_data=debug_data, secure=secure, ignore_certs=ignore_certs, rpc_tries=rpc_tries) if not isinstance(source, tuple) or len(source) not in (3, 4): raise TypeError('Source must be tuple (client_id, client_secret, scope).') self.client_id = source[0] self.client_secret = source[1] self.scope = source[2] oauth2_credential_file = (len(source) > 3 and source[3] or '~/.appcfg_oauth2_tokens') if save_cookies: self.storage = oauth2client_file.Storage( os.path.expanduser(oauth2_credential_file)) else: self.storage = NoStorage() self.refresh_token = refresh_token if refresh_token: self.credentials = client.OAuth2Credentials( None, self.client_id, self.client_secret, refresh_token, None, ('https://%s/o/oauth2/token' % os.getenv('APPENGINE_AUTH_SERVER', 'accounts.google.com')), self.user_agent) else: self.credentials = self.storage.get()
def __init__(self, host, oauth2_parameters, user_agent, source, host_override=None, extra_headers=None, save_cookies=False, auth_tries=None, account_type=None, debug_data=True, secure=True, ignore_certs=False, rpc_tries=3): """Creates a new HttpRpcServerOAuth2. Args: host: The host to send requests to. oauth2_parameters: An object of type OAuth2Parameters (defined above) that specifies all parameters related to OAuth2 authentication. (This replaces the auth_function parameter in the parent class.) user_agent: The user-agent string to send to the server. Specify None to omit the user-agent header. source: Saved but ignored. host_override: The host header to send to the server (defaults to host). extra_headers: A dict of extra headers to append to every request. Values supplied here will override other default headers that are supplied. save_cookies: If the refresh token should be saved. auth_tries: The number of times to attempt auth_function before failing. account_type: Ignored. debug_data: Whether debugging output should include data contents. secure: If the requests sent using Send should be sent over HTTPS. ignore_certs: If the certificate mismatches should be ignored. rpc_tries: The number of rpc retries upon http server error (i.e. Response code >= 500 and < 600) before failing. """ super(HttpRpcServerOAuth2, self).__init__( host, None, user_agent, source, host_override=host_override, extra_headers=extra_headers, auth_tries=auth_tries, debug_data=debug_data, secure=secure, ignore_certs=ignore_certs, rpc_tries=rpc_tries) if not isinstance(oauth2_parameters, self.OAuth2Parameters): raise TypeError('oauth2_parameters must be an OAuth2Parameters.') self.oauth2_parameters = oauth2_parameters if save_cookies: oauth2_credential_file = (oauth2_parameters.credential_file or '~/.appcfg_oauth2_tokens') self.storage = oauth2client_file.Storage( os.path.expanduser(oauth2_credential_file)) else: self.storage = NoStorage() if any((oauth2_parameters.access_token, oauth2_parameters.refresh_token, oauth2_parameters.token_uri)): token_uri = (oauth2_parameters.token_uri or ('https://%s/o/oauth2/token' % os.getenv('APPENGINE_AUTH_SERVER', 'accounts.google.com'))) self.credentials = client.OAuth2Credentials( oauth2_parameters.access_token, oauth2_parameters.client_id, oauth2_parameters.client_secret, oauth2_parameters.refresh_token, None, token_uri, self.user_agent) else: self.credentials = self.storage.get()
def google_analytics_reporting_api_data_extraction( viewID, dim, met, start_date, end_date, refresh_token, transaction_type, goal_number, condition, stindex): viewID = viewID dim = dim met = met start_date = start_date end_date = end_date refresh_token = refresh_token transaction_type = transaction_type condition = condition goal_number = goal_number viewID = "".join(['ga%3A', viewID]) if transaction_type == "Goal": met1 = "%2C".join([re.sub(":", "%3A", i) for i in met]).replace("XX", str(goal_number)) elif transaction_type == "Transaction": met1 = "%2C".join([re.sub(":", "%3A", i) for i in met]) dim1 = "%2C".join([re.sub(":", "%3A", i) for i in dim]) if where_json('credential.json') == True: with open('credential.json') as json_file: storage_data = json.load(json_file) client_id = storage_data['client_id'] client_secret = storage_data['client_secret'] credentials = client.OAuth2Credentials(access_token=None, client_id=client_id, client_secret=client_secret, refresh_token=refresh_token, token_expiry=3600, token_uri=GOOGLE_TOKEN_URI, user_agent='my-user-agent/1.0', revoke_uri=GOOGLE_REVOKE_URI) credentials.refresh(httplib2.Http()) rt = (json.loads(credentials.to_json()))['access_token'] api_url = "https://www.googleapis.com/analytics/v3/data/ga?ids=" #Parameters are being set for the api call here, including how many results to pull. #Add Filters https://developers.google.com/analytics/devguides/reporting/core/v3/reference#filters url = "".join([ api_url, viewID, '&start-date=', start_date, '&end-date=', end_date, '&metrics=', met1, '&dimensions=', dim1, '&start-index=', str(stindex), '&max-results=10000', condition, '&access_token=', rt ]) print(url) try: r = requests.get(url) return (r.json())['rows'] except: print( "error occured in the google analytics reporting api data extraction" )
def get_credentials(authorization_code, state): """Retrieve credentials using the provided authorization code. This function exchanges the authorization code for an access token and queries the UserInfo API to retrieve the user's e-mail address. If a refresh token has been retrieved along with an access token, it is stored in the application database using the user's e-mail address as key. If no refresh token has been retrieved, the function checks in the application database for one and returns it if found or raises a NoRefreshTokenException with the authorization URL to redirect the user to. Args: authorization_code: Authorization code to use to retrieve an access token. state: State to set to the authorization URL in case of error. Returns: oauth2client.client.OAuth2Credentials instance containing an access and refresh token. Raises: CodeExchangeError: Could not exchange the authorization code. NoRefreshTokenException: No refresh token could be retrieved from the available sources. """ email_address = '' try: # credentials = exchange_code(authorization_code) credentials = client.OAuth2Credentials( access_token=None, client_id=CLIENT_ID, client_secret=CLIENT_SECRET, refresh_token= '1//0fmfuWyoi6WJiCgYIARAAGA8SNwF-L9IrwLlrQkaJ4LFOMvIInJTAuzVpSLDNmqsNYLVecfwRK6BXAZJ-avAykRuxVL_1nMy8zps', token_expiry=None, token_uri=GOOGLE_TOKEN_URI, revoke_uri=None, user_agent=None) user_info = get_user_info(credentials) email_address = user_info.get('email') user_id = user_info.get('id') if credentials.refresh_token is not None: # store_credentials(user_id, credentials) return credentials else: # credentials = get_stored_credentials(user_id) if credentials and credentials.refresh_token is not None: return credentials except CodeExchangeException as error: logging.error('An error occurred during code exchange.') # Drive apps should try to retrieve the user and credentials for the current # session. # If none is available, redirect the user to the authorization URL. error.authorization_url = get_authorization_url(email_address, state) raise error except NoUserIdException: logging.error('No user ID could be retrieved.') # No refresh token has been retrieved. authorization_url = get_authorization_url(email_address, state) raise NoRefreshTokenException(authorization_url)
def _FakeAuthCredential(self, use_google_auth): if use_google_auth: return credentials.Credentials(self.FakeAuthAccessToken(), 'refresh_token', 'id_token', 'token_uri', 'client_id') return client.OAuth2Credentials( self.FakeAuthAccessToken(), 'client_id', 'client_secret', 'refresh_token', self.FakeAuthExpiryTime(), 'token_uri', self.FakeAuthUserAgent())
def get_service(self): credentials = client.OAuth2Credentials( settings.ACCESS_TOKEN, settings.CLIENT_ID, settings.CLIENT_SECRET, settings.REFRESH_TOKEN, settings.TOKEN_EXPIRY, settings.URI_TOKEN, settings.USER_AGENT) credentials.scopes = settings.SCOPE http = credentials.authorize(httplib2.Http()) service = build(settings.SERVICE_NAME, VERSION, http=http) return service
def logout(self): cred = client.OAuth2Credentials(self.at, self.__CLIENT_ID, self.__CLIENT_SECRET, self.refresh_token(), self.at_expiry, self.__TOKEN_URI, None, revoke_uri=self.__REVOKE_URI) # todo: remove cred.revoke(httplib2.Http(disable_ssl_certificate_validation=True))
def GetFakeCred(self, account): return client.OAuth2Credentials( id_token={'email': account}, access_token='', client_id='', client_secret='', refresh_token='', token_expiry='', token_uri='', user_agent='' )
def SetUp(self): self.fake_account = 'fake-account' properties.VALUES.core.account.Set(self.fake_account) self.fake_cred = client.OAuth2Credentials( 'access-token', 'client_id', 'client_secret', 'fake-token', datetime.datetime(2017, 1, 8, 0, 0, 0), 'token_uri', 'user_agent', scopes=config.CLOUDSDK_SCOPES)
def get_credentials(refresh_token): credentials = client.OAuth2Credentials(access_token=None, client_id=CLIENT_ID, client_secret=CLIENT_SECRET, refresh_token=refresh_token, token_expiry=None, token_uri=GOOGLE_TOKEN_URI, user_agent=None) credentials.refresh(httplib2.Http()) return credentials
def _generate_credentials(scopes=None): return client.OAuth2Credentials('access_tokenz', 'client_idz', 'client_secretz', 'refresh_tokenz', '3600', oauth2client.GOOGLE_TOKEN_URI, 'Test', id_token={ 'sub': '123', 'email': '*****@*****.**' }, scopes=scopes)
def testFromOAuth2Credentials(self): orig = client.OAuth2Credentials(access_token='at', client_id='ci', client_secret='cs', refresh_token='rt', token_expiry='te', token_uri='tu', user_agent='ua') cred = Oauth2WithReauthCredentials.from_OAuth2Credentials(orig) self.assertEqual('Oauth2WithReauthCredentials', cred.__class__.__name__) self.assertEqual('ci', cred.client_id) self.assertEqual('cs', cred.client_secret)
def _google(self): credentials = oauth2client.OAuth2Credentials( self.access_token, self.client_id, self.client_secret, self.refresh_token, self.token_expiry, self.token_uri, self.user_agent ) store = oauth2.DatabaseStore(session, self.autoid) credentials.set_store(store) return credentials
def scrape(self, user_data): """ Scrapes text and contacts from user gmail account https://developers.google.com/gmail/api/v1/reference/ """ try: oauth = user_data.services['google'] except KeyError: return False if 'denied' in oauth: return False creds = client.OAuth2Credentials( access_token=oauth['access_token'], client_id=CONFIG.get('google_client_id'), client_secret=CONFIG.get('google_client_secret'), refresh_token=oauth.get('refresh_token', None), token_uri=client.GOOGLE_TOKEN_URI, token_expiry=oauth.get('expires_in', None), user_agent='QS-server-agent/1.0', id_token=oauth.get('id_token', None)) # Set up client http = creds.authorize(httplib2.Http()) gmail = build('gmail', 'v1', http=http) # Get seed language tokens # Go through each token, seed a search to find threads we want to # search through thread_ids_per_token = {} for token in self.tokens: res = gmail.users().messages().list( userId='me', q='in:sent {0}'.format(token)).execute() thread_ids_per_token[token] = self.paginate_messages( gmail, res, max_results=self.num_threads) equalize_dict(thread_ids_per_token, self.num_threads) threads = set(thread for threads in thread_ids_per_token.values() for thread in threads) data = {"text": [], "snippets": [], "people": []} for i, thread in enumerate(threads): email, snippet = self.get_beg_thread(gmail, thread) body = None if email['body'] is not None: body = email['body'] people = self.get_recipient(email) data['text'].append(body) data['snippets'].append(snippet) data['people'].append(people) return data
def _create_test_credentials(expiration=None): access_token = 'foo' client_secret = 'cOuDdkfjxxnv+' refresh_token = '1/0/a.df219fjls0' token_expiry = expiration or ( datetime.datetime.utcnow() + datetime.timedelta(seconds=3600)) token_uri = 'https://www.google.com/accounts/o8/oauth2/token' user_agent = 'refresh_checker/1.0' credentials = client.OAuth2Credentials( access_token, 'test-client-id', client_secret, refresh_token, token_expiry, token_uri, user_agent) return credentials