def _get_token(self): """Gets access token Retries if unsuccessful, up to maximum allotment Parameters ---------- None Returns ------- dict a dictionary containing access token and expiration in seconds: {'accessToken': 'token', 'expirationIn': 3600} """ try: response = http_utils.make_request(self._api_endpoint, '/v1/svc-auth/login', method='POST', body={ 'username': self._user, 'password': self._password }) except HTTPError as error: if constants.HTTP_STATUS_CODE['BAD_REQUEST_BODY'] in str(error) or \ constants.HTTP_STATUS_CODE['FAILED_AUTHENTICATION'] in str(error): _exception = InvalidAuthError(error) _exception.__cause__ = None raise _exception raise error return { 'accessToken': response['access_token'], 'expirationIn': response['expires_at'] }
def make_request(self, uri, **kwargs): """Makes request to device (HTTP/S) Parameters ---------- uri : str the URI where the request should be made **kwargs : optional keyword arguments Keyword Arguments ----------------- method : str the HTTP method to use headers : str the HTTP headers to use body : str the HTTP body to use body_content_type : str the HTTP body content type to use bool_response : bool return boolean based on HTTP success/failure advanced_return : bool return additional information, like HTTP status code to caller Returns ------- dict a dictionary containing the JSON response """ return http_utils.make_request(self.host, uri, port=self.port, **kwargs)
def _get_component_versions(self, component_info): """Get component versions Parameters ---------- None Returns ------- dict the component versions { '1.0.0': { 'downloadUrl': '', 'packageName': '', 'latest': True } } """ releases = http_utils.make_request( GITHUB_API_ENDPOINT, '/repos/{}/releases'.format(component_info['repository'])) latest_release_tag_name = http_utils.make_request( GITHUB_API_ENDPOINT, '/repos/{}/releases/latest'.format( component_info['repository']))['tag_name'] ret = {} for release in releases: release_artifacts = self._resolve_artifacts_info( release['tag_name'], release['assets'], component_info) for artifact in release_artifacts: # - "if primary" use the release version as the key # - "if not primary" parse the version from the artifact package name if artifact['is_primary']: release_version = self._normalize_tag_name( release['tag_name']) else: release_version = re.search( VERSION_REGEX, artifact['package_name']).group(0) ret[release_version] = { 'downloadUrl': artifact['download_url'], 'packageName': artifact['package_name'], 'latest': latest_release_tag_name == release['tag_name'] } return ret
def _get_repo_contents(repository, tag): """Get repository contents (from dist folder) Parameters ---------- repository : str repository name tag_name : str repository tag Returns ------- array the repository contents """ return http_utils.make_request( GITHUB_API_ENDPOINT, '/repos/{}/contents/{}?ref={}'.format(repository, 'dist', tag))
def _get_token(self): """Gets authentication token Retries if unsuccessful, up to maximum allotment Parameters ---------- None Returns ------- dict a dictionary containing authentication token, expiration date and expiration in seconds: { 'token': 'token', 'expirationDate': '2019-01-01T01:01:01.00' } """ self.logger.debug('Getting authentication token') response = http_utils.make_request(self.host, '/mgmt/shared/authn/login', port=self.port, method='POST', body={ 'username': self._user, 'password': self._password }, basic_auth={ 'user': self._user, 'password': self._password }) token_details = response['token'] return { 'token': token_details['token'], 'expirationDate': (datetime.now() + timedelta(seconds=token_details['timeout'])).isoformat() }
def _load_metadata(self): """Load extension metadata Load metadata using the follow order: - metadata from CDN (unless use_latest_metadata=False) - metadata included in package (local file) Parameters ---------- None Returns ------- dict a dictionary containg the JSON metadata """ metadata = None # retrieve metadata from URL - unless opted out if self.use_latest_metadata: parsed_url = http_utils.parse_url(EXTENSION_METADATA['URL']) try: metadata = http_utils.make_request(parsed_url['host'], parsed_url['path']) except Exception as err: # pylint: disable=broad-except self.logger.warning('Error downloading metadata file: %s', err) # fallback to local metadata file if metadata is None: local_file = os.path.join(os.path.dirname(__file__), EXTENSION_METADATA['FILE']) try: with open(local_file) as m_file: metadata = json.loads(m_file.read()) except Exception as err: # pylint: disable=broad-except raise FileLoadError(err) return metadata
def make_request(self, uri, **kwargs): """Makes request to service (HTTP/S) Parameters ---------- uri : str the URI where the request should be made **kwargs : optional keyword arguments Keyword Arguments ----------------- method : str the HTTP method to use headers : str the HTTP headers to use body : str the HTTP body to use body_content_type : str the HTTP body content type to use bool_response : bool return boolean based on HTTP success/failure Returns ------- dict a dictionary containing the JSON response """ # merge default authentication headers with any user supplied ones dfl_headers = {AUTH_TOKEN_HEADER: 'Bearer %s' % self.access_token} dfl_headers.update(kwargs.pop('headers', {})) return http_utils.make_request(self._api_endpoint, uri, headers=dfl_headers, **kwargs)
def _get_token(self): """Gets authentication token Retries if unsuccessful, up to maximum allotment Parameters ---------- None Returns ------- dict a dictionary containing authentication token, expiration date and expiration in seconds: {'token': 'token', 'expirationDate': '2019-01-01T01:01:01.00', 'expirationIn': 3600} """ self.logger.debug('Getting authentication token') expiration_date = (datetime.now() + timedelta(hours=1)).isoformat() timeout = 3600 # set timeout to 1 hour uri = '/mgmt/shared/authn/login' body = { 'username': self._user, 'password': self._password, 'loginProviderName': 'tmos' } # get token try: response = http_utils.make_request(self.host, uri, port=self.port, method='POST', body=body, basic_auth={ 'user': self._user, 'password': self._password }) except HTTPError as error: if constants.HTTP_STATUS_CODE['FAILED_AUTHENTICATION'] in str( error): _exception = InvalidAuthError(error) _exception.__cause__ = None raise _exception raise error token = response['token']['token'] # now extend token lifetime token_uri = '/mgmt/shared/authz/tokens/%s' % token http_utils.make_request(self.host, token_uri, port=self.port, method='PATCH', body={'timeout': timeout}, basic_auth={ 'user': self._user, 'password': self._password }) return { 'token': token, 'expirationDate': expiration_date, 'expirationIn': timeout }