def from_config(cls, config): """Returns an initialized Google API object. Args: config: common.ProjectConfig, the project configuration. Returns: An authenticated Google API instance. Raises: AttributeError: if SCOPES, SERVICE, or VERSION are not set. """ if cls.SCOPES is None: raise AttributeError( 'SCOPES must be set in order to create a new {!r} client'.format( cls.__name__)) if cls.SERVICE is None: raise AttributeError( 'SERVICE must be set in order to create a new {!r} client'.format( cls.__name__)) if cls.VERSION is None: raise AttributeError( 'VESRION must be set in order to create a new {!r} client'.format( cls.__name__)) creds = auth.CloudCredentials(config, cls.SCOPES) client = creds.get_api_client(cls.SERVICE, cls.VERSION, cls.SCOPES) return cls(config, client)
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 test_cloud_credentials_constructor(self, mock_creds): """Test the creation of the CloudCredentials object.""" mock_creds.from_authorized_user_info.return_value = TestCredentials([ 'test_scope1', ]) self.fs.CreateFile( self._test_config.local_credentials_file_path, contents=_FAKE_JSON_CONTENTS_ONE) test_creds = auth.CloudCredentials(self._test_config, ['test_scope1']) self.assertEqual(self._test_config, test_creds._config) self.assertEqual(TestCredentials(['test_scope1']), test_creds._credentials)
def from_config(cls, config): """Returns an initialized DatastoreAPI object. Args: config: common.ProjectConfig, the project configuration. Returns: An authenticated DatastoreAPI instance. """ creds = auth.CloudCredentials(config, _SCOPES) client = datastore.Client( project=config.project, credentials=creds.get_credentials(_SCOPES)) return cls(config, client)
def from_config(cls, config, creds=None): """Returns an initialized CloudStorageAPI object. Args: config: common.ProjectConfig, the project configuration. creds: auth.CloudCredentials, the credentials to use for client authentication. Returns: An authenticated CloudStorageAPI instance. """ if creds is None: creds = auth.CloudCredentials(config, cls.SCOPES) client = storage.Client(project=config.project, credentials=creds.get_credentials(cls.SCOPES)) return cls(config, client)
def test_get_api_client(self, mock_creds, mock_build, mock_http_auth): """Test getting a scoped api client.""" mock_creds.from_authorized_user_info.return_value = TestCredentials([ 'test_scope1', ]) self.fs.CreateFile( self._test_config.local_credentials_file_path, contents=_FAKE_JSON_CONTENTS_ONE) test_creds = auth.CloudCredentials(self._test_config, ['test_scope1']) with mock.patch.object( test_creds, '_request_new_credentials', return_value=TestCredentials([ 'test_scope2', 'test_scope1'])) as mock_request: test_api_client = test_creds.get_api_client( 'test_service', 'test_version', ['test_scope2']) del test_api_client # Unused. mock_request.assert_called_once_with(['test_scope2', 'test_scope1']) mock_http_auth.assert_called_once_with( credentials=TestCredentials(['test_scope2', 'test_scope1'])) mock_build.assert_called_once_with( serviceName='test_service', version='test_version', http=mock_http_auth.return_value)
def new(cls, config_file_path, project_key=None): """Creates a new instance of a Grab n Go Manager. Args: config_file_path: str, the name or path to the config file. project_key: Optional[str], the project friendly name, used as the top-level key in the config file. Returns: A new instance of a Grab n Go Manager. Raises: _AuthError: when unable to generate valid credentials. """ if project_key is None: project_key = utils.prompt_string( 'A project name was not provided, which project would you like to ' 'configure?\nNOTE: If you are unsure, or if you plan to use only one ' 'Google Cloud Project, you can use the default.\n' 'The following projects are currently defined in {!r}:\n {}'. format( config_file_path, ', '.join(common.get_available_configs(config_file_path))), default=common.DEFAULT).lower() logging.debug( 'Project key %r was provided, attempting to load from yaml.', project_key) try: config = common.ProjectConfig.from_yaml(project_key, config_file_path) except (common.ConfigError, KeyError) as err: logging.debug( 'Failed to initialize project with key %r: %s\n' 'Attempting to load new config...', project_key, err) utils.write( 'There does not appear to be a saved configuration for this project: ' '{!r}. Before we can get started, we need to gather some information.' '\n'.format(project_key)) config = common.ProjectConfig.from_prompts(project_key, config_file_path) config.write() try: cloud_creds = auth.CloudCredentials(config, _get_oauth_scopes()) except auth.InvalidCredentials as err: utils.write( 'We were unable to create credentials for this configuration, please ' 'verify the Project ID, OAuth2 Client ID and Client Secret are ' 'correct and then re-enter them in the following prompts.') config = common.ProjectConfig.from_prompts(project_key, config_file_path) config.write() return cls.new(config_file_path, project_key) gae_admin_api = app_engine.AdminAPI.from_config(config, cloud_creds) datastore_api = datastore.DatastoreAPI.from_config(config, cloud_creds) directory_api = directory.DirectoryAPI.from_config(config, cloud_creds) storage_api = storage.CloudStorageAPI.from_config(config, cloud_creds) constants = app_constants.get_constants_from_flags() return cls(config, constants, cloud_creds, gae_admin_api, datastore_api, directory_api, storage_api)
def test_cloud_credentials_constructor_invalid_creds(self, mock_run_flow): """Test that an error is raised if credentials cannot be created.""" del mock_run_flow # Unused. with self.assertRaises(auth.InvalidCredentials): auth.CloudCredentials(self._test_config, ['test_scope1'])