Exemplo n.º 1
0
 def _create_sandbox_pay_account(cls, pay_request, user):
     current_app.logger.info('Creating Sandbox Payload %s', pay_request)
     pay_sandbox_accounts_endpoint = f"{current_app.config.get('PAY_API_SANDBOX_URL')}/accounts?sandbox=true"
     RestService.post(endpoint=pay_sandbox_accounts_endpoint,
                      token=user.bearer_token,
                      data=pay_request,
                      raise_for_status=True)
Exemplo n.º 2
0
    def create_key(cls, org_id: int, request_json: Dict[str, str]):
        """Create a key for the account."""
        current_app.logger.debug('<create_key ')
        env = request_json.get('environment', 'sandbox')
        name = request_json.get('keyName')
        org: OrgModel = OrgModel.find_by_id(org_id)
        # first find if there is a consumer created for this account.
        consumer_endpoint: str = current_app.config.get('API_GW_CONSUMERS_API_URL')
        gw_api_key = current_app.config.get('API_GW_KEY') if env == 'prod' else current_app.config.get(
            'API_GW_NON_PROD_KEY')
        email = cls._get_email_id(org_id)

        if not org.has_api_access:  # If the account doesn't have api access, add it
            client_rep = generate_client_representation(org_id, current_app.config.get('API_GW_KC_CLIENT_ID_PATTERN'))
            KeycloakService.create_client(client_rep)
            service_account = KeycloakService.get_service_account_user(client_rep.get('id'))
            KeycloakService.add_user_to_group(service_account.get('id'), GROUP_API_GW_USERS)
            KeycloakService.add_user_to_group(service_account.get('id'), GROUP_ACCOUNT_HOLDERS)

            # Create a consumer with the keycloak client id and secret
            create_consumer_payload = dict(email=email,
                                           firstName=org.name,
                                           lastName=org.branch_name or 'BCR',
                                           userName=org.name,
                                           clientId=client_rep.get('clientId'),
                                           clientSecret=client_rep.get('secret'),
                                           apiAccess=['ALL_API'],
                                           apiKeyName=name)
            api_key_response = RestService.post(
                f'{consumer_endpoint}/mc/v1/consumers',
                additional_headers={'x-apikey': gw_api_key},
                data=create_consumer_payload,
                generate_token=False
            )
            org.has_api_access = True
            org.save()
        else:
            # Create additional API Key if a consumer exists
            api_key_response = RestService.post(
                f'{consumer_endpoint}/mc/v1/consumers/{email}/apikeys',
                additional_headers={'x-apikey': gw_api_key},
                data=dict(
                    apiAccess=['ALL_API'],
                    apiKeyName=name
                ),
                generate_token=False
            )

        return api_key_response.json()
Exemplo n.º 3
0
def validate(is_fatal=False, **kwargs) -> ValidatorResponse:
    """Validate bcol credentials."""
    bcol_credential = kwargs.get('bcol_credential')
    org_id = kwargs.get('org_id', None)
    user: UserContext = kwargs['user']
    validator_response = ValidatorResponse()
    bcol_response = RestService.post(
        endpoint=current_app.config.get('BCOL_API_URL') + '/profiles',
        data=bcol_credential,
        token=user.bearer_token,
        raise_for_status=False)
    if bcol_response.status_code != http_status.HTTP_200_OK:
        error = json.loads(bcol_response.text)
        validator_response.add_error(
            CustomException(error['detail'], bcol_response.status_code))
        if is_fatal:
            raise BusinessException(
                CustomException(error['detail'], bcol_response.status_code),
                None)
    else:
        bcol_account_number = bcol_response.json().get('accountNumber')
        from auth_api.services.org import Org as OrgService  # pylint:disable=cyclic-import, import-outside-toplevel
        if OrgService.bcol_account_link_check(bcol_account_number, org_id):
            validator_response.add_error(Error.BCOL_ACCOUNT_ALREADY_LINKED)
            if is_fatal:
                raise BusinessException(Error.BCOL_ACCOUNT_ALREADY_LINKED,
                                        None)
        else:
            validator_response.add_info({'bcol_response': bcol_response})
    return validator_response
Exemplo n.º 4
0
def _get_pad_confirmation_report_pdf(email_msg, token):
    current_time = datetime.datetime.now()
    mailing_address = _get_address(email_msg.get('accountId'))
    template_vars = {
        **email_msg, 'generatedDate': current_time.strftime('%m-%d-%Y'),
        'accountAddress': mailing_address
    }
    filled_template = generate_template(
        current_app.config.get('PDF_TEMPLATE_PATH'), 'pad_confirmation')
    template_b64 = "'" + base64.b64encode(bytes(filled_template,
                                                'utf-8')).decode() + "'"

    pdf_payload = {
        'reportName': 'PAD_Confirmation_Letter',
        'template': template_b64,
        'templateVars': template_vars,
        'populatePageNumber': True,
    }

    report_response = RestService.post(
        endpoint=current_app.config.get('REPORT_API_BASE_URL'),
        token=token,
        auth_header_type=AuthHeaderType.BEARER,
        content_type=ContentType.JSON,
        data=pdf_payload,
        raise_for_status=True,
        additional_headers={'Accept': 'application/pdf'})
    pdf_attachment = None
    if report_response.status_code != 200:
        logger.error('Failed to get pdf')
    else:
        pdf_attachment = base64.b64encode(report_response.content)

    return pdf_attachment
Exemplo n.º 5
0
    def _create_consumer(cls, name, org, env):
        """Create an API Gateway consumer."""
        consumer_endpoint: str = cls._get_api_consumer_endpoint(env)
        gw_api_key = cls._get_api_gw_key(env)
        email = cls._get_email_id(org.id, env)
        client_rep = generate_client_representation(org.id, current_app.config.get('API_GW_KC_CLIENT_ID_PATTERN'), env)
        KeycloakService.create_client(client_rep)
        service_account = KeycloakService.get_service_account_user(client_rep.get('id'))

        KeycloakService.add_user_to_group(service_account.get('id'),
                                          GROUP_API_GW_USERS if env == 'prod' else GROUP_API_GW_SANDBOX_USERS)
        KeycloakService.add_user_to_group(service_account.get('id'), GROUP_ACCOUNT_HOLDERS)
        # Create a consumer with the keycloak client id and secret
        create_consumer_payload = dict(email=email,
                                       firstName=org.name,
                                       lastName=org.branch_name or 'BCR',
                                       userName=org.name,
                                       clientId=client_rep.get('clientId'),
                                       clientSecret=client_rep.get('secret'),
                                       apiAccess=['ALL_API'],
                                       apiKeyName=name)
        api_key_response = RestService.post(
            f'{consumer_endpoint}/mc/v1/consumers',
            additional_headers={'x-apikey': gw_api_key},
            data=create_consumer_payload,
            generate_token=False
        )
        return api_key_response
Exemplo n.º 6
0
def send_email(notify_body: dict ,token:str):  # pylint:disable=unused-argument
    """Send the email asynchronously, using the given details."""
    current_app.logger.info(f'send_email to {notify_body.get("recipients")}')
    notify_url = current_app.config.get('NOTIFY_API_URL') + '/notify/'
    notify_response = RestService.post(notify_url, token=token, data=notify_body)
    current_app.logger.info('send_email notify_response')
    if notify_response:
        response_json = json.loads(notify_response.text)
        if response_json['notifyStatus']['code'] != 'FAILURE':
            return True

    return False
Exemplo n.º 7
0
    def create_key(cls, org_id: int, request_json: Dict[str, str]):
        """Create a key for the account.

        Steps:
        A - If consumer doesn't exist,
        1 - Create a consumer for PROD and one for SANDBOX
        2 - Keycloak Client created for Sandbox consumer added to sandbox group (new role for sandbox)
        3 - Keycloak client created for PROD consumer added to prod group
        B - If consumer already exists,
        1 - Create key for specific environment.
        """
        current_app.logger.debug('<create_key ')
        env = request_json.get('environment', 'sandbox')
        name = request_json.get('keyName')
        org: OrgModel = OrgModel.find_by_id(org_id)
        # first find if there is a consumer created for this account.
        consumer_endpoint: str = cls._get_api_consumer_endpoint(env)
        gw_api_key = cls._get_api_gw_key(env)
        email = cls._get_email_id(org_id, env)
        if not cls._consumer_exists(email, env):  # If the account doesn't have api access, add it
            # If env is sandbox; then create a sandbox payment account.
            if env != 'prod':
                cls._create_payment_account(org)
            cls._create_consumer(name, org, env=env)
            org.has_api_access = True
            org.save()
            response = cls.get_api_keys(org_id)
        else:
            # Create additional API Key if a consumer exists
            api_key_response = RestService.post(
                f'{consumer_endpoint}/mc/v1/consumers/{email}/apikeys',
                additional_headers={'x-apikey': gw_api_key},
                data=dict(
                    apiAccess=['ALL_API'],
                    apiKeyName=name
                ),
                generate_token=False
            )
            response = api_key_response.json()

        return response
Exemplo n.º 8
0
def send_email(notify_body: dict, token: str):  # pylint:disable=unused-argument
    """Send the email asynchronously, using the given details."""
    current_app.logger.info(f'send_email to {notify_body.get("recipients")}')
    notify_url = current_app.config.get('NOTIFY_API_URL') + '/notify/'
    RestService.post(notify_url, token=token, data=notify_body)
    current_app.logger.info(f'Email sent to {notify_body.get("recipients")}')