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)
    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 from_json(oauth2_return_json: Any):

        """
        Create an OAuth2Return object from json (dictonary or str).
        
        :param oauth2_return_dict: A json dictionary that contains the keys of an OAuth2Return or a string representation of a json dictionary.
        :type oauth2_return_dict:  Any             
        :rtype:                    ibmpairs.authentication.OAuth2Return
        :raises Exception:         if not a dictionary or a string.
        """

        if isinstance(oauth2_return_json, dict):
            oauth2_return = OAuth2Return.from_dict(oauth2_return_json)
        elif isinstance(oauth2_return_json, str):
            oauth2_return_dict = json.loads(oauth2_return_json)
            oauth2_return = OAuth2Return.from_dict(oauth2_return_dict)
        else:
            msg = messages.ERROR_FROM_JSON_TYPE_NOT_RECOGNIZED.format(type(oauth2_return_json), "oauth2_return_json")
            logger.error(msg)
            raise common.PAWException(msg)
        return oauth2_return
    def from_json(basic_json: Any):

        """
        Create an Basic object from json (dictonary or str).
        
        :param basic_dict: A json dictionary that contains the keys of an Basic or a string representation of a json dictionary.
        :type basic_dict:  Any             
        :rtype:            ibmpairs.authentication.Basic
        :raises Exception: if not a dictionary or a string.
        """

        if isinstance(basic_json, dict):
            basic = Basic.from_dict(basic_json)
        elif isinstance(basic_json, str):
            basic_dict = json.loads(basic_json)
            basic = Basic.from_dict(basic_dict)
        else:
            msg = messages.ERROR_FROM_JSON_TYPE_NOT_RECOGNIZED.format(type(basic_json), "basic_json")
            logger.error(msg)
            raise common.PAWException(msg)
        return basic
 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)
Exemple #6
0
    def refresh_auth_token(self):
        '''
        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.
        :returns:            None
        :rtype:              None
        '''

        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: dict = {}
            phoenix_request_body["grant_type"] = "refresh_token"
            phoenix_request_body["client_id"] = self.get_client_id()
            phoenix_request_body[
                "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)

        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(
                    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)
            else:
                msg = messages.ERROR_AUTHENTICATION_PHOENIX_REFRESH_200_RETURN_ERROR.format(
                    response_oauth2_return.error)
                logger.error(msg)
                raise common.PAWException(msg)

        else:
            msg = messages.ERROR_AUTHENTICATION_PHOENIX_NOT_SUCCESSFUL.format(
                str(response))
            logger.error(msg)
            raise common.PAWException(msg)
Exemple #7
0
    def get_auth_token(self, api_key=None, client_id=None, endpoint=None):
        '''
        The method submits a request to the authentication system and obtains a response.
        :param api_key:      An api key for the authentication system.
        :type api_key:       str
        :param client_id:    A client id for the authentication system.
        :type client_id:     str
        :param endpoint:     The authentication endpoint.
        :type endpoint:      str
        :returns:            None
        :rtype:              None
        '''

        response = None
        response_oauth2_return = None

        if api_key is not None:
            self.set_api_key(api_key)
        if client_id is not None:
            self.set_client_id(client_id)
        if endpoint is not None:
            self.set_endpoint(endpoint)

        if (self._api_key is not None) and (self._client_id is not None):

            phoenix_request_headers: dict = {}
            phoenix_request_headers["Content-Type"] = "application/json"
            phoenix_request_headers["Cache-Control"] = "no-cache"

            phoenix_request_body: dict = {}
            phoenix_request_body["apiKey"] = self.get_api_key()
            phoenix_request_body["clientId"] = self.get_client_id()
            phoenix_request_body_json = json.dumps(phoenix_request_body)

            response = requests.post("https://" + self.get_endpoint() +
                                     "/Auth/GetBearerForClient",
                                     headers=phoenix_request_headers,
                                     data=phoenix_request_body_json)

        else:
            msg = messages.ERROR_AUTHENTICATION_NO_API_KEY_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 Exception as ex:
                msg = messages.ERROR_AUTHENTICATION_PHOENIX_RETURN_NOT_OAUTH2RETURN.format(
                    response.json(), ex)
                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)
            else:
                msg = messages.ERROR_AUTHENTICATION_PHOENIX_200_RETURN_ERROR.format(
                    response_oauth2_return.error)
                logger.error(msg)
                raise common.PAWException(msg)

        else:
            msg = messages.ERROR_AUTHENTICATION_PHOENIX_NOT_SUCCESSFUL.format(
                str(response))
            logger.error(msg)
            raise common.PAWException(msg)
Exemple #8
0
def add_dashboard_layer(
    query_registration: QueryRegistrationReturn,
    name: str,
    client=None,
    headers=None,
    host=None,
    style_properties={
        'palette': {
            'COLOR_STEPS': [{
                'step': -1,
                'rgba': [0, 0, 8, 255]
            }, {
                'step': 0,
                'rgba': [11, 0, 251, 255]
            }, {
                'step': .2,
                'rgba': [236, 0, 34, 255]
            }, {
                'step': .4,
                'rgba': [250, 93, 7, 255]
            }, {
                'step': .6,
                'rgba': [250, 249, 0, 255]
            }, {
                'step': .8,
                'rgba': [0, 239, 0, 255]
            }, {
                'step': 1,
                'rgba': [1, 49, 1, 255]
            }]
        },
        'unit': 'C',
        'isInterpolated': True,
        'extendMinimumColor': False,
        'extendMaximumColor': True,
        'invalidDataValue': -9999
    }):
    """
    A method to add a dashboard layer to the IBM Environmental Intelligence Suite (EIS) dashboard.

    :param query_registration: A query registration result from a successful EIS registration.
    :type query_registration:  ibmpairs.dashboard.QueryRegistrationReturn
    :param name:               A dashboard layer name.
    :type name:                str
    :param client:             (Optional) An IBM PAIRS Client.
    :type client:              ibmpairs.client.Client
    :param headers:            (Optional) Headers for the request.
    :type headers:             str
    :param host:               (Optional) A host for the registration.
    :type host:                str
    :param style_properties:   (Optional) A dictionary of style properties for the dashboard layer.
    :type style_properties:    dict
    :raises Exception:         If no client is provided or found Globally in the environment, 
                               if response is not 200.
    """

    if (headers is None):
        headers = constants.CLIENT_JSON_HEADER

    if (host is None):
        host = constants.PHOENIX_ADD_DASHBOARD_LAYER

    if (client is None):
        client = common.set_client(
            input_client=client,
            global_client=client_module.GLOBAL_PAIRS_CLIENT)

    client.set_host(host)

    bodyJson = {
        'VIEWERSHIP_ROLE': 'ALL',
        'CONFIG_BLOCK': {
            'id': name,
            'modelRegistryId': None,
            'displayName': name,
            'provider': None,
            'layerType': 'grid',
            'isSelected': False,
            'isActive': False,
            'enableValidity': False,
            'lastUpdatedUtc': None,
            'coverageArea': 'Custom',
            'dataAttributes': {
                'url': 'https://foundation.agtech.ibm.com/v2',
                'uuid': query_registration.analytics_uuid
            },
            'menuIconUrl': None,
            'legendUrl': '',
            'styleProperties': style_properties
        }
    }

    bodyJsonString = json.dumps(bodyJson)

    try:
        response = client.put(host, body=bodyJsonString, headers=headers)
        if response.status_code != 200:
            try:
                msg = json.dumps(response.json())
            except:
                msg = str(response.status_code)
                logger.error(msg)
            raise common.PAWException(msg)
    except Exception as ex:
        raise ex
    finally:
        # set client back to pointing at PAIRS
        client.set_host(constants.CLIENT_PAIRS_URL)
Exemple #9
0
def register_query(query,
                   query_name: str,
                   client: client_module.Client = None,
                   host: str = None):
    """
    A method to register a PAIRS Query with the IBM Environmental Intelligence Suite (EIS) dashboard.

    :param query:        A PAIRS Query.
    :type query:         ibmpairs.query.Query or dict or str
    :param query_name:   A query name.
    :type query_name:    str
    :param client:       (Optional) An IBM PAIRS Client.
    :type client:        ibmpairs.client.Client
    :param host:         (Optional) A host for the registration.
    :type host:          str
    :returns:            A QueryRegistrationReturn and a Query.
    :rtype:              ibmpairs.dashboard.QueryRegistrationReturn, ibmpairs.query.Query
    :raises Exception:   If no client is provided or found Globally in the environment, 
                         if query type is not ibmpairs.query.Query or dict or str, 
                         if response is not 200, 
                         if object conversions fail.
    """

    if (host is None):
        host = constants.EIS_REGISTER_QUERY_URL

    if (client is None):
        client = common.set_client(
            input_client=client,
            global_client=client_module.GLOBAL_PAIRS_CLIENT)

    client.set_host(host)

    if isinstance(query, query_module.Query):
        query_body = query.to_json()
    elif isinstance(query, dict):
        query_body = json.dumps(query)
    elif isinstance(query, str):
        query_body = query
    else:
        msg = messages.ERROR_QUERY_TYPE_NOT_RECOGNIZED.format(type(query))
        logger.error(msg)
        raise common.PAWException(msg)

    bodyJson = {"pairsPayload": query_body, "analyticsName": query_name}
    bodyJsonString = json.dumps(bodyJson)
    try:
        response = client.post(host, body=bodyJsonString)
        if response.status_code != 200:
            try:
                msg = json.dumps(response.json())
            except:
                msg = str(response.status_code)
            logger.error(msg)
            raise common.PAWException(msg)

        query_registration = QueryRegistrationReturn.from_dict(
            response.json()[0])
        query_return = query_module.QueryResponse(
            id=query_registration.base_computation_id)
        if isinstance(query, query_module.Query):
            query_obj = query
        elif isinstance(query, dict):
            query_obj = query_module.query_from_dict(query)
        else:
            query_obj = query_module.query_from_dict(query)
        query_obj.submit_response = query_return
        query_obj.id = query_registration.base_computation_id
        #query_result = query_module.QueryResult(client=client, query=query_obj, query_return=query_return)
        return query_registration, query_obj
    except Exception as ex:
        raise ex
    finally:
        # set client back to pointing at PAIRS
        client.set_host(constants.CLIENT_PAIRS_URL)