Exemplo n.º 1
0
    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")
Exemplo n.º 2
0
    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")
Exemplo n.º 3
0
    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()
Exemplo n.º 4
0
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)
Exemplo n.º 5
0
    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()
Exemplo n.º 6
0
    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()
Exemplo n.º 7
0
 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()
Exemplo n.º 8
0
    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()
Exemplo n.º 9
0
 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
Exemplo n.º 10
0
 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
Exemplo n.º 11
0
 def _get_url(self, name: str) -> str:
     url = UrlEnum.get(name)
     if not url:
         raise InternalAPIException("URL missing: ", name)
     return url
Exemplo n.º 12
0
 def data(self) -> NoReturn:
     raise InternalAPIException("Should not access all data in a stream response")