def send_jwt_token(self, user, api, subject, info, tag_name): ''' send_jwt_token ''' logger.info('Progressing the process of sending jwt token') jwt_token = self.jwt_generate(user) user_id = user.user_id token = jwt_token['access_token'] session = Session() default_info = {'create_dt': datetime.utcnow(), 'update_dt': datetime.utcnow()} account_info = {'user_id': user_id, 'jwt_token': token} account_obj_info = {**account_info, **default_info} session.query(Account).filter( Account.user_id == user_id).update(account_obj_info) session.commit() link = '{0}{1}?digest={2}'.format( APP_IP, api, jwt_token['access_token']) # formating the e-mail email_context = self.email_formatting( subject, user.email_id, link, info, tag_name) # sending the e-mail self.send_email(email_context)
def email_formatting(self, subject, email_id, link, info, tag_name): ''' Formating the email ''' logger.info('formatting e-mail') email_context = {} email_context['text'] = (link) context = { 'subject': subject, 'info': info, 'link': link, 'tag_name': tag_name } # The subject line for the email. # info = 'Hello, <br/> Welcome to AmzOrbit! We are happy you are here. <br/><br/> First things first, <br/> Let us get started by clicking this link:' email_context['html'] = pystache.render("""<html> <head></head <body> <h1>{{subject}}</h1> <p>{{info}}</p> <a href='{{link}}'>{{tag_name}}</a> </body> </html>""", context) email_context['subject'] = subject email_context['to'] = email_id return email_context
def daily_digest_task(self): ''' Retrieves tenants from user services- User Module Compute the daily digest for each tenant Format the daily digest summary Get the user emails for each tenant Send email to all the users of the tenant ''' tenants = self.user_service.tenants_all() for tenant in tenants: email_list = [] tenant_id = tenant.tenant_id tenant_summary = self.daily_digest_tenant(tenant_id) # send only if product count is not zero if tenant_summary: email_context = self.daily_digest_formatting(tenant_summary) email_context['subject'] = "AMZOrbit: Daily Digest" email_list = self.user_service.users_email_info(tenant_id) email_context['bcc'] = email_list email_context['to'] = '*****@*****.**' if email_list: self.send_email(email_context) logger.info( 'user email id list is empty for the tenant {0} '. format(tenant_id)) else: logger.info('sending daily digest is ignored')
def producer_call(self, product_info): logger.info( 'product info {0} is being sent to the kafka que from the producer' .format(product_info['asin'])) if product_info: ack = self.producer.send('product_to_scrape', {'product_info': product_info}) logger.debug( 'The kafka acknowledgment after sending the message to que {0}' .format(ack)) try: record_metadata = ack.get(timeout=10) logger.info('Record_meta data for kafka que {0}'.format( record_metadata)) except KafkaError: # Decide what to do if produce request failed... logger.error('kafka connection error {0}'.format(KafkaError)) pass else: logger.debug( 'The product info is none so could not send it kafka que')
def jwt_generate(self, user): ''' This method is to generate jwt token ''' logger.info('Jwt token is being generated') token = {'access_token': create_access_token(identity=user)} return token
def password_update(self, account_payload): ''' This method is to update the password Needs to test yet ''' session = Session() user_id = account_payload['user_id'] acc_user = session.query(Account).filter( Account.user_id == user_id).one_or_none() if bcrypt.checkpw(account_payload['old_password'].encode('utf-8'), acc_user.password.encode('utf-8')): updated_pwd = bcrypt.hashpw( account_payload['new_password'].encode('utf-8'), bcrypt.gensalt(12)) default_info = {'create_dt': datetime.utcnow(), 'update_dt': datetime.utcnow()} account_info = {'user_id': user_id, 'password': updated_pwd} account_obj_info = {**account_info, **default_info} session.query(Account).filter( Account.user_id == user_id).update(account_obj_info) session.commit() logger.info( 'Password is sucessfully updated for the user with id {0}'.format(user_id)) return ('success', 'Password Successfully Updated', None) else: return ('error', 'Password Entered is Incorrect', None)
def authenticate_user(self, account_payload): ''' This method is to authenticate the user Takes the username and password. Validates the password with the existing password using bcrypt. Jwt token is sent in response upon succesful authentication ''' session = Session() user_name = account_payload['user_name'] password = account_payload['password'] acc_user = session.query(Account).filter( Account.user_name == user_name).one_or_none() session.commit() if acc_user: if bcrypt.checkpw( password.encode('utf-8'), acc_user.password.encode('utf-8')): jwt_token = self.jwt_generate(acc_user) logger.info( 'User info is validated the authentication is successful for the user {0}'.format(user_name)) return ('success', 'User Authentication Is Successful', jwt_token) else: logger.info( 'User info couldnot be validated for the user name {0}'.format(user_name)) return ('error', 'Either User Name or Password is Incorrect', None)
def post(self): account_payload = request.get_json(force=True) logger.info('Post method is called to autehnticate the use') user = self.user_service.authenticate_user(account_payload) return results(status=user[0], message=user[1], data=user[2], format_json=True)
def get(self): digest_token = request.args.get("digest", '') logger.info('Get method is called to validate the e-mail') user = self.user_service.user_email_validate(digest_token) return results(status=user[0], message=user[1], data=user[2], format_json=True)
def results(status='success', message='', data=[], format_json=True): print('Before the encder in results') logger.info('Before the encoder in results {0}'.format(data)) output_data = json.loads(AlchemyEncoder().encode(data)) output = {'status': status, 'message': message, 'data': output_data} logger.info('The encoded result is {0}'.format(output)) return output
def post(self): account_payload = request.get_json(force=True) account_payload['user_id'] = get_jwt_identity() account_payload['tenant_id'] = get_jwt_claims()['tenant_id'] logger.info('Post method is called to autehnticate the use') user = self.user_service.user_account_create(account_payload) return results(status=user[0], message=user[1], data=user[2], format_json=True)
def tenants_all(self): ''' Returns all tenant-- required for product service module ''' session = Session() tenants = session.query(Tenant).all() logger.info('Retrived all the tenants info') return tenants
def get(self): user_id = get_jwt_identity() tenant_id = get_jwt_claims()['tenant_id'] logger.info('Post method is called to validate the e-mail') user = self.user_service.validate_email_resend(user_id, tenant_id) return results(status=user[0], message=user[1], data=user[2], format_json=True)
def get(self): ''' This controller method is to retrieve the tenant info ''' tenant_id = get_jwt_claims()['tenant_id'] logger.info( 'Get method is called to retrieve the tenant info for the id {0}'.format(tenant_id)) tenant = self.user_service.tenant_get(tenant_id) return results(status=tenant[0], message=tenant[1], data=tenant[2], format_json=True)
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)
def delete(self): ''' This controller method is add delete the user ''' user_id = get_jwt_identity() logger.info( 'Delete method is called to delete the user with the id {0}'.format(user_id)) self.user_service.delete(user_id) return results(status="success", message="User is Deleted!", data='', format_json=True)
def post(self): ''' This method is to update the password ''' user_payload = request.get_json(force=True) logger.info( 'Post method is called to update the password for the user') user = self.user_service.password_reset(user_payload) return results(status=user[0], message=user[1], data=user[2], format_json=True)
def post(self): ''' This controller method is to update the tenant info ''' tenant_payload = request.get_json(force=True) tenant_id = get_jwt_claims()['tenant_id'] logger.info('Post method is called update the tenant info {0} for the id {1}'.format( json.dumps(tenant_payload), tenant_id)) tenant = self.user_service.tenant_update(tenant_id, tenant_payload) return results(status=tenant[0], message=tenant[1], data=tenant[2], format_json=True)
def get(self): ''' This controller method is to retrieve teh card info ''' user_id = get_jwt_identity() tenant_id = get_jwt_claims()['tenant_id'] logger.info('Card info will be retrieved for the user_id {0} and tenant_id {1}'.format( user_id, tenant_id)) # payment = self.payment_service.get(user_id,tenant_id) payment = self.payment_service.get(user_id) return results(status=payment[0], message=payment[1], data=payment[2], format_json=True)
def post(self): ''' This method is to generate jwt token for the given payload ''' jwt_payload = request.get_json(force=True) logger.info( 'JWT token is being generated for the info {0}'.format(jwt_payload)) jwt_token = self.user_service.authenticate_user(jwt_payload) return results(status="success", message="Feteched JWT Token", data=jwt_token, format_json=True)
def post(self): ''' This controller method is to add the user ''' user_payload = request.get_json(force=True) logger.info('Post method is called to register the user with the info {0}'.format( json.dumps(user_payload))) user = self.user_service.register(user_payload) return results(status=user[0], message=user[1], data=user[2], format_json=True)
def get(self): ''' This controller method is to retrieve teh use info ''' user_id = get_jwt_identity() tenant_id = get_jwt_claims()['tenant_id'] logger.info('User info will be retrieved for the user_id {0} and tenant_id {1}'.format( user_id, tenant_id)) user = self.user_service.get(user_id, tenant_id) return results(status=user[0], message=user[1], data=user[2], format_json=True)
def post(self): ''' This controller method is to add the user ''' payment_payload = request.get_json(force=True) payment_payload['payment_payload']['user_id'] = get_jwt_identity() # user_payload['tenant_id'] = get_jwt_claims()['tenant_id'] logger.info('Post method is called to register the user with the info {0}'.format( json.dumps(payment_payload['payment_payload']['user_id']))) payment = self.payment_service.addPayment(payment_payload) return results(status=payment[0], message=payment[1], data=payment[2], format_json=True)
def get(self): ''' This controller method is to retrieve all the alerts for the given tenant ''' tenant_id = get_jwt_claims()['tenant_id'] logger.info( 'Get method is called to retrieve all the alerts for the tenant {0}' .format(tenant_id)) alert = self.alert_service.search({}, tenant_id) return results(status="success", message="Fetched Alert", data=alert, format_json=True)
def get(self): ''' This method is to validate JWT token ''' # digest_token = reqparse.RequestParser() # digest_token.add_argument( # 'digest', type=str, help='digest cannot be converted') parser = reqparse.RequestParser() parser.add_argument('digest', type=str) logger.info( 'Get method is called to validate the token ') user = self.user_service.validate_jwt_token(parser.parse_args()) return results(status=user[0], message=user[1], data=user[2], format_json=True)
def aletrnate_names_create(self, attribute): ''' This is a global method to create user friendly names ''' logger.info( 'Retrieving the alternate user friendly name for the attribute {} in the alert module' .format(attribute)) alternate_names = AlertService.alternate_names if attribute in alternate_names.keys(): return alternate_names[attribute] return attribute
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
def get(self, user_id, tenant_id): ''' This method retrieves the user info ''' session = Session() user = session.query(User).filter( User.user_id == user_id).filter( User.tenant_id == tenant_id).one_or_none() if user is None: logger.error('User with user_id {0} and tenant_id {1} doesnot exist'.format( user_id, tenant_id)) return ('error', 'User doesnt exist', None) logger.info('User info is retreived for the user_id {0} and tenant_id {1} with the user info {2}'.format( user_id, tenant_id, user.email_id)) return ('success', 'User Info Retrieved', user)
def users_email_info(self, tenant_id): ''' Sends email list for users related to tenant- required for product service module ''' email_list = [] session = Session() users = session.query(User).filter(User.tenant_id == tenant_id).filter(User.email_validation == True).filter( User.email_daily_digest == True).all() if users: for user in users: if user.email_id and user.email_id not in email_list: email_list.append(user.email_id) logger.info( 'Email list of all the users is composed for the tenant {0}'.format(tenant_id)) return email_list
def post(self): ''' This controller method is to update the user info ''' user_payload = request.get_json(force=True) user_payload['user_id'] = get_jwt_identity() user_payload['tenant_id'] = get_jwt_claims()['tenant_id'] logger.info( 'Post method is called to update the user info for the user_id {0} and tenant_id {1}' .format(user_payload['user_id'], user_payload['tenant_id'])) user = self.user_service.update(user_payload) return results(status=user[0], message=user[1], data=user[2], format_json=True)