def connect_impl(self, creds): log.debug('Connecting to box') if not self.__client or creds != self.__creds: try: if creds: self.__creds = creds else: raise CloudTokenError("no creds") jwt_token = creds.get('jwt_token') access_token = creds.get('access_token') refresh_token = creds.get('refresh_token') if not jwt_token: if not ((self._oauth_config.app_id and self._oauth_config.app_secret) and (refresh_token or access_token)): raise CloudTokenError("require app_id/secret and either access_token or refresh token") with self._mutex: box_session = Session() box_kwargs = box_session.get_constructor_kwargs() box_kwargs["api_config"] = boxsdk.config.API box_kwargs["default_network_request_kwargs"] = {"timeout": 60} if jwt_token: jwt_dict = json.loads(jwt_token) user_id = creds.get('user_id') auth = JWTAuth.from_settings_dictionary(jwt_dict, user=user_id, store_tokens=self._store_refresh_token) else: if not refresh_token: raise CloudTokenError("Missing refresh token") auth = OAuth2(client_id=self._oauth_config.app_id, client_secret=self._oauth_config.app_secret, access_token=access_token, refresh_token=refresh_token, store_tokens=self._store_refresh_token) box_session = AuthorizedSession(auth, **box_kwargs) self.__client = Client(auth, box_session) with self._api(): self.__access_token = auth.access_token self._long_poll_manager.start() except BoxNetworkException as e: log.exception("Error during connect %s", e) self.disconnect() raise CloudDisconnectedError() except (CloudTokenError, CloudDisconnectedError): raise except Exception as e: log.exception("Error during connect %s", e) self.disconnect() raise CloudTokenError() with self._api() as client: return client.user(user_id='me').get().id
def get_box_client() -> Client: # pylint: disable=global-statement global BOX_ACCESS_AGE global BOX_CLIENT if not Client or not JWTAuth: raise Exception('Could not import necessary Box Library.') if BOX_CLIENT is not None and BOX_ACCESS_AGE is not None and datetime.now( ) - BOX_ACCESS_AGE < timedelta(minutes=MAX_BOX_ACCESS_AGE): return BOX_CLIENT response = boto3.client('secretsmanager').get_secret_value( SecretId=BOX_API_ACCESS_NAME) settings = build_jwt_settings(response) BOX_CLIENT = Client(JWTAuth.from_settings_dictionary(settings)) BOX_ACCESS_AGE = datetime.now() return BOX_CLIENT
def _load_auth(cls, auth_data): """Load JWTAuth from Box service account JSON keyfile Args: auth_data (dict): The loaded keyfile data from a Box service account JSON file Returns: boxsdk.JWTAuth Instance of JWTAuth that allows the client to authenticate or False if there was an issue loading the auth """ try: auth = JWTAuth.from_settings_dictionary(auth_data) except (TypeError, ValueError, KeyError): LOGGER.exception('Could not load JWT from settings dictionary') return False return auth
def get_client(service_account): """ Attempts to create the Box Client with the associated with the credentials. """ try: if os.path.isfile(service_account): auth = JWTAuth.from_settings_file(service_account) else: service_dict = json.loads(service_account) auth = JWTAuth.from_settings_dictionary(service_dict) client = Client(auth) client.user().get() return client except BoxOAuthException as e: print(f'Error accessing Box account with pervice account ' \ f'developer_token={developer_token}; client_id={client_id}; ' \ f'client_secret={client_secret}') raise (e)
def get_box_client() -> Client: # pylint: disable=global-statement global BOX_ACCESS_AGE global BOX_CLIENT fips_enabled = os.getenv('ENABLE_FIPS', '').lower() == 'true' fips_suffix = '-fips.' + os.getenv('AWS_REGION', '') + '.amazonaws.com' if not Client or not JWTAuth: raise Exception('Could not import necessary Box Library.') if BOX_CLIENT is not None and BOX_ACCESS_AGE is not None and datetime.now( ) - BOX_ACCESS_AGE < timedelta(minutes=MAX_BOX_ACCESS_AGE): return BOX_CLIENT response = boto3.client( 'secretsmanager', endpoint_url='https://secretsmanager' + fips_suffix if fips_enabled else None).get_secret_value( SecretId=BOX_API_ACCESS_NAME) settings = build_jwt_settings(response) BOX_CLIENT = Client(JWTAuth.from_settings_dictionary(settings)) BOX_ACCESS_AGE = datetime.now() return BOX_CLIENT
def get_box_client() -> Client: # pylint: disable=global-statement global BOX_ACCESS_AGE global BOX_CLIENT fips_enabled = os.getenv("ENABLE_FIPS", "").lower() == "true" fips_suffix = "-fips." + os.getenv("AWS_REGION", "") + ".amazonaws.com" if not Client or not JWTAuth: raise Exception("Could not import necessary Box Library.") if (BOX_CLIENT is not None and BOX_ACCESS_AGE is not None and datetime.now() - BOX_ACCESS_AGE < timedelta(minutes=MAX_BOX_ACCESS_AGE)): return BOX_CLIENT response = boto3.client( "secretsmanager", endpoint_url="https://secretsmanager" + fips_suffix if fips_enabled else None, ).get_secret_value(SecretId=BOX_API_ACCESS_NAME) settings = build_jwt_settings(response) BOX_CLIENT = Client(JWTAuth.from_settings_dictionary(settings)) BOX_ACCESS_AGE = datetime.now() return BOX_CLIENT