def _authenticate(self, username: str, password: str): with Connection(self._connection_info) as conn: token_request = { "grant_type": "password", "username": username, "password": password, } basic_auth = base64.b64encode("{}:{}".format( self._oauth_client_id, self._oauth_client_secret).encode("utf-8")) headers = { "Content-type": "application/x-www-form-urlencoded", "Authorization": "Basic {}".format(basic_auth.decode("utf-8")), } try: conn.request( "POST", self._get_url(UrlEnum.AUTH.TOKEN), body=urllib.parse.urlencode(token_request), headers=headers, ) except (OSError, HTTPException) as e: raise InternalAPIException(str(e)) response = conn.getresponse() if response.status != 200: raise InternalAPIException("Invalid response: ", response.status) data = response.read() self._access_token = json.loads(data).get("access_token") if self._access_token == "": raise InternalAPIException("Failed to get access token")
def _authenticate(self, username: str, password: str) -> None: # saving the creds for the re-auth purposes self._initialize_api_client_credentials(username, password) with Connection(self._connection_info) as conn: token_request = { "grant_type": "password", "username": username, "password": password, } basic_auth = base64.b64encode("{}:{}".format( self._oauth_client_id, self._oauth_client_secret).encode("utf-8")) headers = { "Content-type": "application/x-www-form-urlencoded", "Authorization": "Basic {}".format(basic_auth.decode("utf-8")), } try: conn.request( "POST", self._get_url(UrlEnum.AUTH.TOKEN), body=urllib.parse.urlencode(token_request), headers=headers, ) except (OSError, HTTPException) as e: raise InternalAPIException(e) response = conn.getresponse() if response.status != 200: raise InternalAPIException("Invalid response: ", response.status) try: data = json.loads(response.read()) except (JSONDecodeError, TypeError) as e: raise InternalAPIException(e) from e # privx response includes access token age in seconds self._access_token_age = data.get("expires_in") self._re_auth_deadline = (int(time.time()) + self._access_token_age - self._re_auth_margin) self._access_token = data.get("access_token") if self._access_token == "": raise InternalAPIException("Failed to get access token")
def _http_get_no_auth(self, url_name: str) -> Tuple: request = self._build_request("GET", url_name) headers = request["headers"] del headers["Authorization"] with Connection(self._connection_info) as conn: try: conn.request(**request) except (OSError, HTTPException) as e: raise InternalAPIException(e) response = conn.getresponse() return response.status, response.read()
def format_path_components(format_str: str, **kw) -> str: try: components = {k: urllib.parse.quote(v, safe="") for k, v in kw.items()} except TypeError: incorrect_params = { k: f"{type(v).__name__}" for k, v in kw.items() if isinstance(v, str) is False } error_message = (f"Expect argument type str but got:\n" f"{json.dumps(incorrect_params, indent=4)}") raise InternalAPIException(error_message) return format_str.format(**components)
def _http_get_no_auth(self, urlname: str) -> tuple: headers = self._get_headers() del headers["Authorization"] with Connection(self._connection_info) as conn: try: conn.request( "GET", self._build_url(urlname), headers=headers, ) except (OSError, HTTPException) as e: raise InternalAPIException(str(e)) response = conn.getresponse() return response.status, response.read()
def _http_get(self, urlname: str, path_params=None, query_params=None) -> tuple: path_params = path_params or {} query_params = query_params or {} with Connection(self._connection_info) as conn: try: conn.request( "GET", self._build_url(urlname, path_params, query_params), headers=self._get_headers(), ) except (OSError, HTTPException) as e: raise InternalAPIException(str(e)) response = conn.getresponse() return response.status, response.read()
def _http_stream( self, url_name: str, body: Optional[dict] = None, path_params: Optional[dict] = None, query_params: Optional[dict] = None, ) -> HTTPResponse: conn = Connection(self._connection_info).connect() try: conn.request(**self._build_request( "GET", url_name, path_params, query_params, body=body, )) except (OSError, HTTPException) as e: raise InternalAPIException(e) return conn.getresponse()
def _http_get( self, url_name: str, path_params: Optional[dict] = None, query_params: Optional[dict] = None, ) -> Tuple: with Connection(self._connection_info) as conn: try: conn.request(**self._build_request( "GET", url_name, path_params, query_params, )) except (OSError, HTTPException) as e: raise InternalAPIException(e) response = conn.getresponse() return response.status, response.read()
def get_context(self) -> ssl.SSLContext: try: context = ssl.create_default_context(cadata=self.ca_cert) except ssl.SSLError as e: raise InternalAPIException(e) return context
def _initialize_api_client_credentials(self, username: str, password: str): # check if arguments are None or empty string if {username, password} & {None, ""}: raise InternalAPIException("api client credentials are not valid") self._api_client_id = username self._api_client_password = password
def _get_url(self, name: str) -> str: url = UrlEnum.get(name) if not url: raise InternalAPIException("URL missing: ", name) return url
def data(self) -> NoReturn: raise InternalAPIException("Should not access all data in a stream response")