def refresh_auth_token(self,
                           verify    = constants.GLOBAL_SSL_VERIFY
                          ):
        
        """
        The method submits a request to the authentication system for a refreshed token, gets a response and updates the internal self._oauth2_return and self._jwt_token objects.
        """
        
        msg = messages.INFO_AUTHENTICATION_TOKEN_REFRESH
        logger.info(msg)
        
        response               = None
        response_oauth2_return = None

        if (self._oauth2_return is not None) and (self._oauth2_return._refresh_token is not None) and (self._client_id is not None):
            
            phoenix_request_headers: dict             = {}
            phoenix_request_headers["Content-Type"]   = "application/x-www-form-urlencoded"
            phoenix_request_headers["Cache-Control"]  = "no-cache"

            phoenix_request_body = "grant_type=refresh_token" + \
                                   "&client_id=" + self.get_client_id() + \
                                   "&refresh_token=" + self.oauth2_return.get_refresh_token()

            response = requests.post("https://" + 
                                         self.get_endpoint() +
                                         "/connect/token",
                                     headers = phoenix_request_headers,
                                     data    = phoenix_request_body,
                                     verify  = verify
                                    )
        else:
            msg = messages.ERROR_AUTHENTICATION_NO_REFRESH_TOKEN_OR_CLIENT_ID
            logger.error(msg)
            raise common.PAWException(msg)
            
        if response.status_code == 200:
            try:
                response_oauth2_return = oauth2_return_from_dict(response.json())
            except:
                msg = messages.ERROR_AUTHENTICATION_PHOENIX_RETURN_NOT_OAUTH2RETURN.format("/connect/token", response.json())
                logger.error(msg)
                raise common.PAWException(msg)
            
            if response_oauth2_return.error is None:
                self.set_jwt_token(response_oauth2_return.access_token)
                self.set_oauth2_return(response_oauth2_return)
                msg = messages.INFO_AUTHENTICATION_TOKEN_REFRESH_SUCCESS
                logger.info(msg)
            else:
                msg = messages.ERROR_AUTHENTICATION_PHOENIX_REFRESH_200_RETURN_ERROR.format("/connect/token", response_oauth2_return.error)
                logger.error(msg)
                raise common.PAWException(msg)
                
        else:
            msg = messages.ERROR_AUTHENTICATION_PHOENIX_NOT_SUCCESSFUL.format("/connect/token", str(response))
            logger.error(msg)
            raise common.PAWException(msg)
Exemple #2
0
    def __init__(self,
                 host: str = 'pairs.res.ibm.com',
                 username: str = None,
                 api_key: str = None,
                 api_key_file: str = "ibmpairspass.txt",
                 client_id: str = "ibm-pairs",
                 endpoint: str = "auth-b2b-twc.ibm.com",
                 jwt_token: str = None) -> None:
        '''
        The method initializes the instance of the class.
        :param host:         The host to execute requests against.
        :type host:          str
        :param username:     A username for the user.
        :type username:      str
        :param api_key:      An api key for the user.
        :type api_key:       str
        :param api_key_file: An file which stores the api key.
        :type api_key_file:  str
        :param client_id:    A client id for the authentication system.
        :type client_id:     str
        :param endpoint:     The authentication endpoint.
        :type endpoint:      str
        :param jwt_token:    A jwt token for authentication.
        :type jwt_token:     str
        :returns:            None
        :rtype:              None
        '''

        self._host = host
        self._username = username
        self._api_key = api_key
        self._api_key_file = api_key_file
        self._client_id = client_id
        self._endpoint = endpoint
        self._jwt_token = jwt_token

        self._oauth2_return = OAuth2Return()

        if ((self._api_key is None) and (self._username is not None)):
            try:
                self.set_credentials_from_file(self._username,
                                               self._api_key_file, self._host)
            except:
                msg = messages.INFO_AUTHENTICATION_API_KEY_NOT_FOUND_IN_FILE.format(
                    username, api_key_file, host)
                logger.info(msg)

        if (self._api_key is not None):
            try:
                self.get_auth_token(api_key=self._api_key,
                                    client_id=self._client_id,
                                    endpoint=self._endpoint)
            except Exception as ex:
                msg = messages.INFO_AUTHENTICATION_COULD_NOT_GET_AUTH_TOKEN.format(
                    api_key, ex)
                logger.info(msg)
 def set_api_key_file(self, api_key_file):
     
     if os.path.isfile(os.path.join(os.getcwd(), api_key_file)):
         self._api_key_file = os.path.join(os.getcwd(), api_key_file)
     elif os.path.isfile(api_key_file):
         self._api_key_file = common.check_str(api_key_file)
     else:
         msg = messages.ERROR_AUTHENTICATION_COULD_NOT_FIND_API_KEY_FILE.format(api_key_file)
         logger.info(msg)
         raise common.PAWException(msg)
Exemple #4
0
def check_bool(b: Any) -> bool:
    '''
    The method checks if a boolean value, or a string or int that can validly be inferred 
    to be boolean is found. If 'true' or 'false' (to lowercase) or '0' or '1' are 
    found, they are transformed appropriately to a bool.

    :param b:           The input value to check.
    :type b:            Any
    :returns:           A boolean of appropriate value 'True' or 'False'
    :rtype:             bool
    :raises Exception:  If the type of 'b' is not in ['bool', 'string' or 'int'].
                        If the value of 'b' is a string but not (when converted to lowercase) 'true' or 'false'.
                        If the value of 'b' is an integer but not '1' or '0'.
    '''

    bo = None

    if isinstance(b, bool):
        bo = b
    elif isinstance(b, str):
        if b.lower() == 'true':
            bo = True
            msg = messages.INFO_COMMON_CHECK_BOOL_CONVERSION.format(
                type(b), str(b), 'True')
            logger.info(msg)
        elif b.lower() == 'false':
            bo = False
            msg = messages.INFO_COMMON_CHECK_BOOL_CONVERSION.format(
                type(b), str(b), 'False')
            logger.info(msg)
        else:
            msg = messages.ERROR_COMMON_CHECK_BOOL_STRING_NOT_BOOL.format(
                str(b))
            logger.error(msg)
            raise PAWException(msg)
    elif isinstance(b, int):
        if b == 1:
            bo = True
            msg = messages.INFO_COMMON_CHECK_BOOL_CONVERSION.format(
                type(b), str(b), 'True')
            logger.info(msg)
        elif b == 0:
            bo = False
            msg = messages.INFO_COMMON_CHECK_BOOL_CONVERSION.format(
                type(b), str(b), 'False')
            logger.info(msg)
        else:
            msg = messages.ERROR_COMMON_CHECK_BOOL_INT_NOT_BOOL.format(str(b))
            logger.error(msg)
            raise PAWException(msg)
    else:
        msg = messages.ERROR_COMMON_CHECK_BOOL.format(type(bo), str(bo))
        logger.error(msg)
        raise PAWException(msg)

    return bo
    def __init__(self,
                 host: str         = constants.CLIENT_PAIRS_URL,
                 username: str     = None,
                 api_key: str      = None,
                 api_key_file: str = "auth/oauth2.txt",
                 client_id: str    = "ibm-pairs",
                 endpoint: str     = "auth-b2b-twc.ibm.com",
                 jwt_token: str    = None,
                ):

        self._host          = common.strip_protocol(host)
        self._username      = username
        self._api_key       = api_key
        self._api_key_file  = api_key_file
        self._client_id     = client_id
        self._endpoint      = endpoint
        self._jwt_token     = jwt_token
        
        self._oauth2_return = OAuth2Return()
        
        if ((self._api_key is None) and (self._username is not None)):
            try:
                self.set_credentials_from_file(self._username,
                                               self._api_key_file, 
                                               self._host
                                              )
            except:
                msg = messages.INFO_AUTHENTICATION_API_KEY_NOT_FOUND_IN_FILE.format(self._username, self._api_key_file, self._host)
                logger.info(msg)
        
        if (self._api_key is not None):
            try:
                self.get_auth_token(api_key   = self._api_key,
                                    client_id = self._client_id, 
                                    endpoint  = self._endpoint
                                   )
            except Exception as ex:
                msg = messages.INFO_AUTHENTICATION_COULD_NOT_GET_AUTH_TOKEN.format(api_key, ex)
                logger.info(msg)
                
        if self._jwt_token is None:
            msg = messages.ERROR_AUTHENTICATION_FAILED.format("JWT token")
            logger.error(msg)
            raise common.PAWException(msg)
 def __init__(self,
              host: str          = constants.CLIENT_PAIRS_URL,
              username: str      = None,
              password: str      = None,
              password_file: str = "auth/basic.txt"
             ):
     self._host          = common.strip_protocol(host)
     self._username      = username
     self._password      = password
     self._password_file = password_file
     
     if ((self._password is None) and (self._username is not None)):
         try:
             self.set_credentials_from_file(self._username, self._password_file, self._host)
         except Exception as e:
             msg = messages.INFO_AUTHENTICATION_PASSWORD_NOT_FOUND_IN_FILE.format(self._username, self._password_file, self._host)
             logger.info(msg)
     
     if (self._password is None) or (self._username is None):
         msg = messages.ERROR_AUTHENTICATION_FAILED.format('username and password')
         logger.error(msg)
         raise common.PAWException(msg)