def aec_processor(self):
        try:
            webhook_secret = self.config_file['webhookSecret']
            encoded_jwt = cherrypy.request.headers['AUTHENTICATION'].replace(
                "Bearer ", "")
            decoded_jwt = jwt_parser.decode(encoded_jwt,
                                            webhook_secret,
                                            algorithms=['HS256'])
            logger.error(decoded_jwt)
            if "webhook_id" in decoded_jwt:
                tier_request = TierFulfillment(
                    Config(
                        api_url=self.config_file['quickStart']['url'],
                        api_key=self.config_file['quickStart']['key'],
                        products=self.config_file['quickStart']['products']))

                tier_request.process()

                request = ProductFulfillment(
                    Config(
                        api_url=self.config_file['quickStart']['url'],
                        api_key=self.config_file['quickStart']['key'],
                        products=self.config_file['quickStart']['products']))

                request.process()
        except Exception as err:
            logger.error(err)
    def _upload_spreadsheet(self, usage_file, spreadsheet):
        # type: (UsageFile, openpyxl.Workbook) -> None

        # Generate spreadsheet file
        with NamedTemporaryFile() as tmp:
            spreadsheet.save(tmp)
            tmp.seek(0)
            file_contents = tmp.read()

        # Setup request
        url = self._api.get_url(usage_file.id + '/upload/')
        headers = self._api.headers
        headers['Accept'] = 'application/json'
        del headers[
            'Content-Type']  # This must NOT be set for multipart post requests
        multipart = {'usage_file': ('usage_file.xlsx', file_contents)}
        logger.info('HTTP Request: {} - {} - {}'.format(
            url, headers, multipart))

        # Post request
        try:
            content, status = self._api.post(path=usage_file.id + '/upload/',
                                             headers=headers,
                                             files=multipart)
        except requests.RequestException as ex:
            raise FileCreationError('Error uploading file: {}'.format(ex))
        logger.info('HTTP Code: {}'.format(status))
        if status != 201:
            msg = 'Unexpected server response, returned code {}'.format(status)
            logger.error('{} -- Raw response: {}'.format(msg, content))
            raise FileCreationError(msg)
 def _update_conversation_if_exists(conversation, request_id, obj):
     # type: (Optional[Conversation], str, object) -> None
     if conversation:
         try:
             conversation.add_message(str(obj))
         except TypeError as ex:
             logger.error(
                 'Error updating conversation for request {}: {}'.format(
                     request_id, ex))
示例#4
0
    def __purchase(self, req):
        logger.info("PURCHASE")
        setattr(self, 'tenant', None)
        login_name = req.asset.get_param_by_id('customer_admin').value
        # Check if logged user exists
        self.service.check_login(login_name)
        try:
            # Create customer account
            logger.info("Creating tenant...")
            tenant_created = self.service.provision_customer(
                req.id,
                self.get_tier_config(req.asset.tiers.tier1.id,
                                     self.config.products[0]).get_param_by_id(
                                         'tenant_id').value)
            logger.debug(tenant_created)
            setattr(self, 'tenant', tenant_created['id'])
            # Set offering based in sku
            logger.info("Setting offerings...")
            self.service.set_customer_offerings(
                tenant_created['id'],
                self.get_tier_config(req.asset.tiers.tier1.id,
                                     self.config.products[0]).get_param_by_id(
                                         'tenant_id').value,
                [
                    Utils.sku_to_offering_item(item)
                    for item in req.asset.items if item.quantity > 0
                ])
            # Create admin for user account
            logger.info("Creating admin...")
            admin_created = self.service.create_admin(tenant_created,
                                                      login_name)
            logger.debug(admin_created)
            # Create access policies for created user
            self.service.access_policies(admin_created, tenant_created)
            # Send activation email
            self.service.send_email(login_name, admin_created)
            params = [
                Param(id='customer_tenant_id',
                      value=str(tenant_created['id'])),
            ]
            self.update_parameters(req.id, params)
            logger.info("PURCHASE END")

        except Exception as err:
            if self.tenant:
                logger.error("Rollback tenant creation")
                suspended = self.service.edit(self.tenant, {
                    'enabled': False,
                    'version': 1
                })
                self.service.remove(self.tenant, suspended['version'],
                                    {'version': suspended['version']})
            raise FailRequest(err)
    def send_request(verb, uri, config, body=None):
        logger.error("REQUEST------------------->")
        logger.error('Request: %s %s' % (verb, uri))
        logger.debug(body)

        options = {
            'url': uri,
            'headers': {
                'Content-Type': config['Content-Type']
            }
        }

        if 'bearer' in config:
            options['headers']['Authorization'] = 'Bearer ' + config['bearer']
        elif 'basic' in config:
            options['headers']['Authorization'] = 'Basic ' + config['basic']

        if body:
            options['data'] = urlencode(body, quote_via=quote_plus) if config[
                'Content-Type'] == 'application/x-www-form-urlencoded' else json.dumps(
                    body)

        response = api.request(verb, **options)

        if 200 <= response.status_code <= 300:
            logger.debug(str(response))
            if response.content:
                return response.json()
        else:
            logger.error('Response')
            logger.error(str(response))
            raise Exception(response.json()['error'])
 def reset(req):
     partner_config = Utils.get_partner_data(
         {'connection': req.configuration.connection.id, 'tier_1': req.configuration.account.external_id,
          'tier_2': 'default', 'req_id': req.configuration.id})
     logger.error("PARTNER CONFIG###############################################################################")
     logger.error(partner_config)
     api = Utils.get_api(partner_config)
     api.send_reset_email(
         {
             "login": req.get_param_by_id('admin_login_name').value,
             "email": req.configuration.account.contact_info.contact.email,
             "user_id": req.get_param_by_id('admin_id').value
         }
     )
 def aec_actions(self, jwt):
     webhook_secret = self.config_file['actionsSecret']
     decoded_jwt = jwt_parser.decode(jwt,
                                     webhook_secret,
                                     algorithms=['HS256'])
     automation = TierConfigAutomation()
     filters = automation.filters(
         status='approved',
         configuration__id=decoded_jwt['configuration_id'],
         configuration__product__id=self.config_file['quickStart']
         ['products'])
     tier_requests = automation.list(filters)
     request = tier_requests[0]
     if decoded_jwt['action_id'] == 'SSO':
         link = Actions.sso(request)
         logger.error("LINK: " + link)
         raise cherrypy.HTTPRedirect(link)
     elif decoded_jwt['action_id'] == 'RESET':
         Actions.reset(request)
    def get_usage_template(self, product):
        """ Returns the template file contents for a specified product.

        :param Product product: Specific product.
        :return: The template file contents.
        :rtype: bytes
        :raises FileRetrievalError: Raised if the file contents could not be retrieved.
        """
        location = self._get_usage_template_download_location(product.id)
        if not location:
            msg = 'Error obtaining template usage file location'
            logger.error(msg)
            raise FileRetrievalError(msg)

        contents = self._retrieve_usage_template(
            location) if location else None
        if not contents:
            msg = 'Error obtaining template usage file from `{}`'.format(
                location)
            logger.error(msg)
            raise FileRetrievalError(msg)
        return contents
示例#9
0
    def process_request(self, req: Fulfillment) -> object:
        try:
            logger.info("Processing request " + req.id)
            partner_config = Utils.get_partner_data(req)
            setattr(self, 'service',
                    Service(partner_config, req.asset.tiers.customer))

            switcher = {
                "purchase": lambda: __class__.__purchase(self, req),
                "cancel": lambda: __class__.__cancel(self, req),
                "change": lambda: __class__.__change(self, req),
                "suspend": lambda: __class__.__toggle(self, False, req),
                "resume": lambda: __class__.__toggle(self, True, req)
            }

            switcher.get(req.type, "ERROR: Action type is no valid")()

            if req.type in ['purchase', 'change', 'resume']:
                result = ActivationTemplateResponse(
                    partner_config['templates']['activation_template'])
            else:
                result = ActivationTileResponse('Operation ' + req.type +
                                                ' done successfully')
            logger.info("Finishing request " + req.id)
            return result
        except SkipRequest as err:
            logger.info(err.message)
            raise SkipRequest(str(err))
        except FailRequest as err:
            logger.error(
                "Issue while processing Purchase request. Print Error: %s" %
                str(err))
            raise err
        except InquireRequest as err:
            logger.error(
                "Issue while processing Purchase request. Print Error: %s" %
                str(err))
            raise err
        except Exception as err:
            logger.error(
                "Issue while processing Purchase request. Print Error: %s" %
                str(err))

            raise err
示例#10
0
    def migrate(self, request):
        """ Call this function to perform migration of one request.

        :param Fulfillment request: The request to migrate.
        :return: A new request object with the parameter values updated.
        :rtype: Fulfillment
        :raises SkipRequest: Raised if migration fails for some reason.
        :raises MigrationParamError: Raised if the value for a parameter is not a string.
        """
        if request.needs_migration(self.migration_key):
            logger.info(
                '[MIGRATION::{}] Running migration operations for request {}'.
                format(request.id, request.id))
            request_copy = copy.deepcopy(request)

            raw_data = request.asset.get_param_by_id(self.migration_key).value
            logger.debug('[MIGRATION::{}] Migration data `{}`: {}'.format(
                request.id, self.migration_key, raw_data))

            try:
                try:
                    parsed_data = json.loads(raw_data)
                except ValueError as ex:
                    raise MigrationAbortError(str(ex))
                logger.debug(
                    '[MIGRATION::{}] Migration data `{}` parsed correctly'.
                    format(request.id, self.migration_key))

                # These will keep track of processing status
                processed_params = []
                succeeded_params = []
                failed_params = []
                skipped_params = []

                # Exclude param for migration_info from process list
                params = [
                    param for param in request_copy.asset.params
                    if param.id != self.migration_key
                ]

                for param in params:
                    # Try to process the param and report success or failure
                    try:
                        if param.id in self.transformations:
                            # Transformation is defined, so apply it
                            logger.info(
                                '[MIGRATION::{}] Running transformation for parameter {}'
                                .format(request.id, param.id))
                            param.value = self.transformations[param.id](
                                parsed_data, request.id)
                            succeeded_params.append(param.id)
                        elif param.id in parsed_data:
                            # Parsed data contains the key, so assign it
                            if not isinstance(parsed_data[param.id],
                                              six.string_types):
                                if self.serialize:
                                    parsed_data[param.id] = json.dumps(
                                        parsed_data[param.id])
                                else:
                                    type_name = type(
                                        parsed_data[param.id]).__name__
                                    raise MigrationParamError(
                                        'Parameter {} type must be str, but {} was given'
                                        .format(param.id, type_name))
                            param.value = parsed_data[param.id]
                            succeeded_params.append(param.id)
                        else:
                            skipped_params.append(param.id)
                    except MigrationParamError as ex:
                        logger.error('[MIGRATION::{}] {}'.format(
                            request.id, ex))
                        failed_params.append(param.id)

                    # Report processed param
                    processed_params.append(param.id)

                logger.info(
                    '[MIGRATION::{}] {} processed, {} succeeded{}, {} failed{}, '
                    '{} skipped{}.'.format(
                        request.id, len(processed_params),
                        len(succeeded_params),
                        self._format_params(succeeded_params),
                        len(failed_params), self._format_params(failed_params),
                        len(skipped_params),
                        self._format_params(skipped_params)))

                # Raise abort if any params failed
                if failed_params:
                    raise MigrationAbortError(
                        'Processing of parameters {} failed, unable to complete migration.'
                        .format(', '.join(failed_params)))
            except MigrationAbortError as ex:
                logger.error('[MIGRATION::{}] {}'.format(request.id, ex))
                raise SkipRequest('Migration failed.')

            return request_copy
        else:
            logger.info(
                '[MIGRATION::{}] Request does not need migration.'.format(
                    request.id))
            return request
def error_page_500(status, message, traceback, version):
    logger.error(status)
    logger.error(message)
    return "500 Error!"
示例#12
0
    def process_request(self, req):
        try:
            setattr(self, 'tenant', None)
            if req.type == 'update':
                raise FailRequest("Update operations are not allowed")
            logger.info("Begin tier config process:" + req.configuration.id)
            logger.debug(req)
            partner_config = Utils.get_partner_data(
                {'connection': req.configuration.connection.id, 'tier_1': req.configuration.account.external_id,
                 'tier_2': 'default', 'req_id': req.id})

            logger.info(
                "Validate if req requires Skip according accountExternalIdsConfigRequestSkipPrefix config parameter")
            if req.configuration.account.external_id.startswith(
                    tuple(partner_config['accountExternalIdsConfigRequestSkipPrefix'])):
                raise SkipRequest('Skipped by processor configuration')
            setattr(self, 'service', Service(partner_config, req.configuration.account))
            # Check if current logged user exists
            self.service.check_login(req.get_param_by_id('admin_login_name').value)

            subs_start = str(time.time())
            internal_tag = 'aps-abc-start-prod-date=%s;aps-abc-tier=%s;aps-abc-billing-model=%s' % (
                subs_start, '-1', 'per_gb')

            # Create tenant subscription
            logger.info("Creating tenant...")
            tenant_created = self.service.create_tenant(req.id, internal_tag)
            logger.debug(tenant_created)
            setattr(self, 'tenant', tenant_created['id'])
            # Create admin for subscription
            logger.info("Creating admin...")
            admin_created = self.service.create_admin(tenant_created,
                                                      req.get_param_by_id('admin_login_name').value, True)
            logger.debug(admin_created)
            # Add access policies for the user
            logger.info("Adding access policies...")
            self.service.access_policies(admin_created, tenant_created, True)
            # Set offerings available for reseller customers
            logger.info("Set offerings...")
            self.service.set_offerings(tenant_created)
            # Send activation email
            logger.info("Sending email...")
            self.service.send_email(req.get_param_by_id('admin_login_name').value, admin_created)

            params = [
                Param(id='tenant_id', value=str(tenant_created['id'])),
                Param(id='admin_id', value=str(admin_created['id'])),
                Param(id='reseller_customer_id', value=str(internal_tag)),
                Param(id='billing_date', value=str(subs_start))
            ]
            logger.info("End tier configuration for " + req.configuration.id)
            self.update_parameters(req.id, params)
            return ActivationTemplateResponse(partner_config['templates']['t1_template'])

        except FailRequest as err:
            self.__rollback()
            logger.error("Issue while processing Purchase request. Print Error: %s" % err)
            raise err
        except SkipRequest as err:
            logger.info(err)
            raise err
        except InquireRequest as err:
            self.__rollback()
            if self.tenant:
                self.service.remove(self.tenant)
            logger.error("Issue while processing Purchase request. Print Error: %s" % err)
            raise err
        except Exception as err:
            self.__rollback()
            if self.tenant:
                self.service.remove(self.tenant)
            logger.error("Issue while processing Purchase request. Print Error: %s" % err)
            raise err
 def sso(req):
     logger.error("SSO####################################################")
     partner_config = Utils.get_partner_data(
         {'connection': req.configuration.connection.id, 'tier_1': req.configuration.account.external_id,
          'tier_2': 'default', 'req_id': req.id})
     api = Utils.get_api(partner_config)
     reseller_id = req.get_param_by_id('tenant_id').value
     admin_id = req.get_param_by_id('admin_id').value
     logger.error("GROUP")
     group = api.get_group_id(reseller_id)
     console_branded = api.get_acc_console_branded(str(group['id']))
     logger.error("CONSOLE BRANDED")
     logger.error(console_branded)
     logger.error("JWT")
     jwt_data = api.sso(admin_id)
     link = console_branded['account_server_url']+'?jwt='+jwt_data['jwt']
     logger.error(link)
     return link