Пример #1
0
    def user_email_validate(self, token):
        '''
         This method is to validate the email
        '''
        session = Session()

        # calling method to decode the token
        data = self.jwt_token_decode(token)

        # Extracting the user_id and tenant_id from the decoded data of the payload
        user_id = data['identity']
        tenant_id = data['user_claims']['tenant_id']

        user = session.query(User).filter(
            User.user_id == user_id).filter(
            User.tenant_id == tenant_id).one_or_none()

        if user is None:
            return ('error', 'Unable to verify the account, please request again', None)
        else:

            user.email_validation = True
            session.add(user)
            session.commit()

            return('success', 'E-mail is successfully validated', None)
Пример #2
0
    def account_create(self, account_payload):
        '''
            This method is to create the account for the user

            User name and password are manadatory
        '''

        logger.info('an account is being created with the user name {0}'.format(
            account_payload['user_name']))
        session = Session()

        account_exists = self.account_verify(account_payload['user_name'])

        default_info = {'create_dt': datetime.utcnow(),
                        'update_dt': datetime.utcnow()}

        hashed_pwd = bcrypt.hashpw(
            account_payload['password'].encode('utf-8'), bcrypt.gensalt(12))

        account_info = {'user_name': account_payload['user_name'], 'password': hashed_pwd,
                        'user_id': account_payload['user_id'], 'tenant_id': account_payload['tenant_id']}
        account_obj_info = {**account_info, **default_info}
        account_obj = Account(**account_obj_info)

        if not account_exists:
            session.add(account_obj)
            session.commit()
            logger.info('An account is created for the user {0}'.format(
                account_obj.user_name))
        else:
            logger.info('An account already exists with the user name {0}'.format(
                account_info['user_name']))
            return ('error', 'An Account already exists for the user', None)

        return ('success', 'Account successfully created', None)
Пример #3
0
    def addPayment(self, payload):
        ''' 
            This method is for the payment information insertion. 

        '''
        session = Session()

        default_info = {'create_dt': datetime.utcnow(),
                        'update_dt': datetime.utcnow()}

        payment = payload['payment_payload']

        subscription = payload['subscription']
        plan_id = subscription['plan_id']
        stripe_token = payment['id']
        user_id = payment['user_id']

        logger.info('Payment information is being added for the prospective user with the given user name {0}'.format(
            payment['card']['name']))

        payment_payload = {'last4': payment['card']['last4'], 'brand': payment['card']['brand'],
                           'exp_month': payment['card']['exp_month'], 'exp_year': payment['card']['exp_year'],
                           'name': payment['card']['name'], 'stripe_token': payment['id'], 'user_id': payment['user_id']}

        payment_obj = {**payment_payload, **default_info}
        payment = Payment(**payment_obj)
        session.add(payment)

        plan = session.query(Subscription).filter(
            Subscription.id == plan_id).one_or_none()

        # logger.info('plan id is  {0}'.format(plan.plan_id))

        user = session.query(User).filter(
            User.user_id == user_id).one_or_none()

        user_email_id = user.email_id

        # stripe_token should be a source id

        customer_id = stripe.Customer.create(
            email=user_email_id,
            source=stripe_token,
        )
        logger.info('customer id :{0} '.format(customer_id))

        subscription = stripe.Subscription.create(
            customer=customer_id,
            items=[{'plan': plan.plan_id}],
        )
        # update subscription_expiry to "valid"
        user.suscription_expiry = None
        user.subscription_id = plan.id
        session.add(user)
        session.commit()

        return ('success', 'Payment is Successful', None)
Пример #4
0
    def user_create(self, user_payload):
        '''
        A method to create an user
        '''

        session = Session()

        default_info = {'create_dt': datetime.utcnow(),
                        'update_dt': datetime.utcnow()}

        logger.info('User registration is in progress')
        user_obj = {**user_payload, **default_info}
        user = User(**user_obj)
        session.add(user)
        session.commit()

        return user
Пример #5
0
    def tenant_create(self, tenant_name):
        '''
            This method is to create the tenant.

            Tenant name can be null
        '''

        session = Session()

        default_info = {'create_dt': datetime.utcnow(),
                        'update_dt': datetime.utcnow()}

        tenant_obj_info = {**{'tenant_name': tenant_name}, **default_info}
        tenant = Tenant(**tenant_obj_info)
        session.add(tenant)
        session.commit()
        logger.info(
            'Tenant is created with the id {0}'.format(tenant.tenant_id))
        return tenant.tenant_id
Пример #6
0
    def delete(self, productId, tenant_id):
        '''
            This method is delete the product for a given tenant

            The product archive status will be set to true rather than deleting the info

        '''

        session = Session()

        logger.info(
            'The product with product_id {0} and tenant_id {1} is being archived'
            .format(productId, tenant_id))

        product_id = {'id': productId}
        product = Product(**product_id)

        product = session.query(Product).filter(
            Product.id == product.id).filter(
                Product.tenant_id == int(tenant_id)).one_or_none()
        product.archive = True
        session.add(product)
        session.commit()
Пример #7
0
    def add(self, products):
        '''
            This method is to add new product(s) in the db

            It checks if the products exists or archvied earlier.

            If archived, it sets the archive to false

            A few default attributes will be added

            Once the products are added, the product info will be sent to kafka que for further scraping
        '''

        session = Session()

        product_list = []
        ideal_state = {}
        added_products = []
        existing_products = []
        invalid_products = []

        default_input = {
            'health_status': 'Healthy',
            'ideal_state': json.dumps(ideal_state),
            'product_info_status': 'Pending Update',
            'create_dt': datetime.utcnow(),
            'created_by': products['user_id'],
            'title': 'Hold Tight! We are Retrieving Product Info',
            'archive': False,
            'tenant_id': int(products['tenant_id'])
        }

        for product_info in products['products']:

            if len(product_info['asin'].strip()) == 10:

                default_input['uid'] = str(uuid.uuid1())
                product_info['asin'] = product_info['asin'].strip()

                product_input = {**product_info, **default_input}
                product = Product(**product_input)

                instance = session.query(Product).filter(
                    Product.asin == product.asin).filter(
                        Product.tenant_id == int(
                            products['tenant_id'])).one_or_none()

                archived_product = session.query(Product).filter(
                    Product.asin == product.asin).filter(
                        Product.tenant_id == int(products['tenant_id'])
                    ).filter(Product.archive == True).one_or_none()

                if instance == None and archived_product == None:
                    logger.debug(
                        'The product with asin {0} is being added'.format(
                            product_info['asin']))
                    product_list.append(product)
                    added_products.append({'asin': product_info['asin']})

                elif archived_product != None:

                    logger.debug(
                        'The product {0} is being retrieved from the archived state'
                        .format(product_info['asin']))

                    archived_product.archive = False
                    session.add(archived_product)

                else:

                    logger.debug('The product {0} already exists'.format(
                        product_info['asin']))

                    existing_products.append({
                        'asin':
                        product_info['asin'],
                        'message':
                        'This asin is already present so ignored'
                    })

                session.add_all(product_list)
                session.commit()

            else:
                logger.info('The given asin {0} is invalid'.format(
                    product_info['asin']))

                invalid_products.append({
                    'asin': product_info['asin'],
                    'message': 'Invalid asin length'
                })

        products_new = session.query(Product).filter(
            Product.product_info_status == 'Pending Update').filter(
                Product.archive != True).filter(
                    Product.tenant_id == int(products['tenant_id'])).all()

        for instance in products_new:

            logger.info(
                'The product {0} is added and being sent to kafka que for scraping'
                .format(instance.asin))

            self.kafkaproducer_call(self.row2dict(instance))
            # wait for 1-3 seconds for each product
            sleep(randint(1, 3))

        status = {
            'success': added_products,
            'warning': existing_products,
            'error': invalid_products
        }
        return status