Ejemplo n.º 1
0
    def _consumer_exists(cls, email, env):
        """Return if customer exists with this email."""
        consumer_endpoint: str = cls._get_api_consumer_endpoint(env)
        gw_api_key: str = cls._get_api_gw_key(env)
        try:
            RestService.get(
                f'{consumer_endpoint}/mc/v1/consumers/{email}',
                additional_headers={'x-apikey': gw_api_key}
            )
        except HTTPError as exc:
            if exc.response.status_code == 404:  # If consumer doesn't exist
                return False
            raise exc

        return True
Ejemplo n.º 2
0
def upgrade():
    # Query all orgs which are linked to BCOL.
    conn = op.get_bind()
    org_res = conn.execute(
        "select o.id, o.bcol_user_id from orgs o where bcol_user_id is not null and bcol_account_id is not null and status_code in ('ACTIVE', 'PENDING_STAFF_REVIEW');"
    )
    orgs = org_res.fetchall()
    print('starting migration for BCOL products')
    if len(orgs) > 0:
        token = RestService.get_service_account_token()
    for org_id in orgs:
        try:
            print('Getting bcol profile for ', org_id[0], org_id[1])
            bcol_response = RestService.get(
                endpoint=current_app.config.get('BCOL_API_URL') +
                f'/profiles/{org_id[1]}',
                token=token)
            print('BCOL Response', bcol_response.json())
            Product.create_subscription_from_bcol_profile(
                org_id[0],
                bcol_response.json().get('profileFlags'))
        except Exception as exc:
            print('Profile Error')
            print(exc)
            raise exc
    db.session.commit()
Ejemplo n.º 3
0
    def get_api_keys(cls, org_id: int) -> List[Dict[str, any]]:
        """Get all api keys."""
        current_app.logger.debug('<get_api_keys ')
        consumer_endpoint: str = current_app.config.get('API_GW_CONSUMERS_API_URL')
        gw_api_key: str = current_app.config.get('API_GW_KEY')

        email_id = cls._get_email_id(org_id)
        try:
            consumers_response = RestService.get(
                f'{consumer_endpoint}/mc/v1/consumers/{email_id}',
                additional_headers={'x-apikey': gw_api_key}
            )
            api_keys = consumers_response.json()
        except HTTPError as exc:
            if exc.response.status_code == 404:
                api_keys = {}
            else:
                raise exc

        return api_keys
Ejemplo n.º 4
0
    def get_api_keys(cls, org_id: int) -> List[Dict[str, any]]:
        """Get all api keys."""
        current_app.logger.debug('<get_api_keys ')
        check_auth(one_of_roles=(ADMIN, STAFF), org_id=org_id)
        api_keys_response = {'consumer': {'consumerKey': []}}
        for env in ('sandbox', 'prod'):
            email = cls._get_email_id(org_id, env)
            consumer_endpoint: str = cls._get_api_consumer_endpoint(env)
            gw_api_key: str = cls._get_api_gw_key(env)

            try:
                consumers_response = RestService.get(
                    f'{consumer_endpoint}/mc/v1/consumers/{email}',
                    additional_headers={'x-apikey': gw_api_key}
                )
                keys = consumers_response.json()['consumer']['consumerKey']
                cls._filter_and_add_keys(api_keys_response, keys, email)
            except HTTPError as exc:
                if exc.response.status_code != 404:  # If consumer doesn't exist
                    raise exc

        return api_keys_response
Ejemplo n.º 5
0
async def process_name_events(event_message: Dict[str, any]):
    """Process name events.

    1. Check if the NR already exists in entities table, if yes apply changes. If not create entity record.
    2. Check if new status is DRAFT, if yes call pay-api and get the account details for the payments against the NR.
    3. If an account is found, affiliate to that account.

    Args:
        event_message (object): cloud event message, sample below.
            {
                'specversion': '1.0.1',
                'type': 'bc.registry.names.events',
                'source': '/requests/6724165',
                'id': id,
                'time': '',
                'datacontenttype': 'application/json',
                'identifier': '781020202',
                'data': {
                    'request': {
                        'nrNum': 'NR 5659951',
                        'newState': 'APPROVED',
                        'previousState': 'DRAFT'
                    }
                }
            }
    """
    logger.debug('>>>>>>>process_name_events>>>>>')
    request_data = event_message.get('data').get('request')
    nr_number = request_data['nrNum']
    nr_status = request_data['newState']
    nr_entity = EntityModel.find_by_business_identifier(nr_number)
    if nr_entity is None:
        logger.info('Entity doesn' 't exist, creating a new entity.')
        nr_entity = EntityModel(business_identifier=nr_number,
                                corp_type_code=CorpType.NR.value)

    nr_entity.status = nr_status
    nr_entity.name = request_data.get(
        'name',
        '')  # its not part of event now, this is to handle if they include it.
    nr_entity.last_modified_by = None  # TODO not present in event message.
    nr_entity.last_modified = parser.parse(event_message.get('time'))

    if nr_status == 'DRAFT' and AffiliationModel.find_affiliations_by_business_identifier(
            nr_number) is None:
        logger.info('Status is DRAFT, getting invoices for account')
        # Find account details for the NR.
        invoices = RestService.get(
            f'{APP_CONFIG.PAY_API_URL}/payment-requests?businessIdentifier={nr_number}',
            token=RestService.get_service_account_token()).json()

        # Ideally there should be only one or two (priority fees) payment request for the NR.
        if invoices and (auth_account_id := invoices['invoices'][0].get('paymentAccount').get('accountId')) \
                and str(auth_account_id).isnumeric():
            logger.info('Account ID received : %s', auth_account_id)
            # Auth account id can be service account value too, so doing a query lookup than find_by_id
            org: OrgModel = db.session.query(OrgModel).filter(
                OrgModel.id == auth_account_id).one_or_none()
            if org:
                nr_entity.pass_code_claimed = True
                # Create an affiliation.
                logger.info(
                    'Creating affiliation between Entity : %s and Org : %s',
                    nr_entity, org)
                affiliation: AffiliationModel = AffiliationModel(
                    entity=nr_entity, org=org)
                affiliation.flush()
Ejemplo n.º 6
0
 def _get_pay_account(cls, org, user):
     pay_accounts_endpoint = f"{current_app.config.get('PAY_API_URL')}/accounts/{org.id}"
     pay_account = RestService.get(endpoint=pay_accounts_endpoint, token=user.bearer_token).json()
     return pay_account