def test_shopee_auth_call_back_failure(shopee_api, client, access_token, test_user, set_env_for_shopee): """ case where shopee call returned an error like wrong signature, missing parameters """ shopee_api.return_value = { 'msg': 'Authentication signature calculation is wrong', 'request_id': '7b1rfhxN35gTCjHQ0RKlDY', 'error': 'error_auth' } res = client.post("/auth/shopee_auth_callback", headers={ 'content-type': 'application/json', 'Authorization': 'Bearer ' + access_token }, json={ "shop_id": 124761188 } ) user = User.find_user_by_username(test_user.username) marketplace = ShopeeMarketplace.query.filter_by(user=user, shop_id=124761188).first() assert marketplace is None res_json = json.loads(res.data) assert res_json.get("error") is not None assert res.status_code == 200
def post(self): """Authenticate user and return token""" if not request.is_json: return {'error': 'Missing JSON in request'} email = request.json.get('email', None) password = request.json.get('password', None) user = User.find_user_by_email(email.lower()) if user is None or not pwd_context.verify(password, user.password): return {'error': 'Invalid email or password'}, 401 access_token = create_access_token(identity=user.id) refresh_token = create_refresh_token(identity=user.id) user_dump = UserSchema().dump(user).data user_dump.pop("password", None) user_dump.pop("email_logs", None) return { 'access_token': access_token, 'refresh_token': refresh_token, 'user': user_dump }
def test_lazada_auth_callback_successful(lazada_api, client, access_token, test_user): """ case where lazada call was successful and returned access token and there was no error updating user record """ lazada_api.return_value = Mock(body={u'account': u'*****@*****.**', u'code': u'0', u'access_token': u'50000800b29fOwiBo0RvahylWcLPbtQC6fAP3PR2j19472a42JmRjyluZknrA0', u'country': u'ph', u'expires_in': 604800, u'request_id': u'0b8fda7b15501212252766562', u'refresh_expires_in': 2592000, u'account_platform': u'seller_center', u'country_user_info': [{u'short_code': u'PHJ2F8MX', u'country': u'ph', u'seller_id': u'1000069977', u'user_id': u'100255018'}], u'refresh_token': u'50001800e29jhdwoqeD4g2cnSZVOeYDAP7KRtHFmQ145db664K4ltvHgdjzjcV'}, message=None) res = client.post("/auth/lazada_auth_callback", headers={ 'content-type': 'application/json', 'Authorization': 'Bearer ' + access_token }, json={ "code": "0_108647_7LaCotddGRvLahUEPXdev1R92743" } ) user = User.find_user_by_username(test_user.username) marketplace = LazadaMarketplace.query.filter_by(user=user, seller_id='1000069977').first() assert marketplace.country == 'ph' assert marketplace.access_token == '50000800b29fOwiBo0RvahylWcLPbtQC6fAP3PR2j19472a42JmRjyluZknrA0' assert marketplace.refresh_token == '50001800e29jhdwoqeD4g2cnSZVOeYDAP7KRtHFmQ145db664K4ltvHgdjzjcV' assert marketplace.access_token_expiration == 604800 assert marketplace.refresh_token_expiration == 2592000 assert json.loads(res.data).get("user_id") == user.id assert json.loads(res.data).get("seller_id") == '1000069977' assert res.status_code == 200 assert user.active_country.lower() == 'ph'
def post(self): """ Start of password recovery. System generates reset password token and sends it to the email user specified. """ email = request.json.get('email') if not email: return {'error': 'No email in request.'} user = User.find_user_by_email(email) if not user: return {'error': 'No user found for this email.'} ResetToken.query.filter_by(user_id=user.id).delete() reset_token = ResetToken(user_id=user.id, token_str=str(uuid.uuid4())) db.session.add(reset_token) try: db.session.commit() except Exception as e: db.session.rollback() traceback.print_exc() return { 'error': None, 'msg': 'Failed to save reset token to database.' } if not current_app.testing: # @TODO actually send the email using SendGrid return {'error': None, 'msg': 'Successfully sent email.'}
def delete(self): """ Cancels the current membership for the user. """ user_id = get_jwt_identity() current_user = User.get(user_id) user_object_id = current_user.id customer_id = current_user.customer_id try: membership_utils.cancel_membership(user_object_id, customer_id) except Exception as e: return { 'error': 'Failed to delete membership: {}'.format(e) } current_user.cancel_membership() try: db.session.commit() return { 'error': None, "msg": "Successfully deleted membership." } except Exception as e: db.session.rollback() return { 'error': 'Failed to delete membership: {}'.format(e) }
def admin_user(db): user = User( username='******', email='*****@*****.**', password='******', role='admin' ) db.session.add(user) db.session.commit() return user
def another_test_user(db): user = User( user_id="123", username='******', email='*****@*****.**', password='******', role='user' ) db.session.add(user) db.session.commit() return user
def test_user(db): user = User( username='******', email='*****@*****.**', password='******', role='user', marketplace_id='test_marketplace_id', has_active_subscription=True ) db.session.add(user) db.session.commit() return user
def get(self): """ Gets the current membership data for the user. """ user_id = get_jwt_identity() current_user = User.get(user_id) customer_id = current_user.customer_id try: data = membership_utils.get_membership_data(customer_id) except Exception as e: return { 'error': 'Failed to get membership data: {}.'.format(e) } return {'data': json.dumps(data, indent=4)}
def put(self): experience_data = request.json experience_id = experience_data['id'] experience = Experience.query.filter( Experience.id == experience_id ).first() if not experience: return { 'status': 'error', 'message': 'experience not found.' }, 400 for key, value in experience_data.items(): if key == 'category' and value.lower() not in VALID_CATEGORY: return { 'status': 'error', 'message': 'invalid category' }, 400 if key != id: setattr(experience, key, value) if key == 'start_date' or key == 'end_date': setattr(experience, 'epoch_{}'.format(key), generate_epoch_from_string_datetime(value)) user = User.get(get_jwt_identity()) setattr(experience, 'last_updated_at', datetime.datetime.utcnow().isoformat()) setattr(experience, 'epoch_last_updated_at', int(time.time())) setattr(experience, 'last_updated_by', user.id) try: db.session.commit() created_by = experience.user.full_name experience = ExperienceSchema().dump(experience).data experience['created_by'] = created_by return { 'status': 'success', 'experience': experience } except Exception as e: db.session.rollback() return { 'status': 'error', 'message': 'failed update to database' }, 422
def post(self): """Authenticate user and return token""" if not request.is_json: return {'error': 'Missing JSON in request'} username = request.json.get('username', None) if not username: return {'error': 'Missing username'} user = User.find_user_by_username(username.lower()) if user is None: return {'error': 'Bad credentials'} access_token = create_access_token(identity=user.id) refresh_token = create_refresh_token(identity=user.id) ret = {'access_token': access_token, 'refresh_token': refresh_token} return ret
def post(self): """ Updates the billing method for the current user. """ stripe_token = request.get_json().get('stripeToken') if not stripe_token: return { 'error': 'Failed to update billing because we did not receive a stripe token.' } user_id = get_jwt_identity() current_user = User.get(user_id) customer_id = current_user.customer_id try: return membership_utils.update_billing(customer_id, stripe_token) except Exception as e: return { 'error': 'Failed to update billing: {}'.format(e) }
def init(): """Init application, create database tables and create a new user named admin with password admin """ from rodenia_api.extensions import db from rodenia_api.models import User click.echo("create database") db.create_all() click.echo("done") click.echo("create user") user = User(username='******', business_name="admin_business", email='*****@*****.**', password='******', role="admin") db.session.add(user) db.session.commit() click.echo("created user admin")
def test_shopee_auth_call_back_successful(shopee_api, enqueue_call, client, access_token, test_user, set_env_for_shopee): """ case where shopee call was successful and it returned shop's info in dict """ shopee_api.return_value = { "status": "NORMAL", "item_limit": 10000, "disable_make_offer": 0, "videos": [], "country": "PH", "shop_description": "", "shop_id": 124761188, "request_id": "Hz9q28LazQgEqDQclw4MK", "images": [], "shop_name": "essramos", "enable_display_unitno": False } res = client.post("/auth/shopee_auth_callback", headers={ 'content-type': 'application/json', 'Authorization': 'Bearer ' + access_token }, json={ "shop_id": 124761188 } ) assert enqueue_call.call_count == len(SHOPEE_ORDER_STATUS_ENUM) user = User.find_user_by_username(test_user.username) marketplace = ShopeeMarketplace.query.filter_by(user=user, shop_id=124761188).first() # print(res.data) # print(db.engine.table_names()) # print(marketplace, user) assert marketplace.country == 'PH' assert user.active_country == 'PH' assert marketplace.shop_id == 124761188 assert json.loads(res.data).get("shop_id") == 124761188 assert json.loads(res.data).get("user_id") == user.id assert res.status_code == 200
def post(self): experience_data = request.json experience = Experience( category=Categories.MUSIC ) for key, value in experience_data.items(): if key == 'category' and value.lower() not in VALID_CATEGORY: return { 'status': 'error', 'message': 'invalid category' }, 400 setattr(experience, key, value) user = User.get(get_jwt_identity()) setattr(experience, 'epoch_start_date', generate_epoch_from_string_datetime(experience_data['start_date'])) setattr(experience, 'epoch_end_date', generate_epoch_from_string_datetime(experience_data['end_date'])) setattr(experience, 'created_by', user.id) db.session.add(experience) try: db.session.commit() created_by = experience.user.full_name experience = ExperienceSchema().dump(experience).data experience['created_by'] = created_by return { 'status': 'success', 'experience': experience }, 201 except Exception as e: db.session.rollback() return { 'status': 'error', 'message': 'failed save to database' }, 422
def post(self): """ Restarts the membership for the current user. """ user_id = get_jwt_identity() current_user = User.get(user_id) customer_id = current_user.customer_id try: membership_utils.restart_membership(user_id, customer_id) except Exception as e: return { 'error': 'Failed to restart membership: {}'.format(e) } current_user.restart_membership() try: db.session.commit() return { 'error': None, 'msg': 'Successfully restarted membership.' } except Exception as e: db.session.rollback() return { 'error': 'Failed to restarted membership: {}'.format(e) }
def post(self): experience_data = request.json experience_id = experience_data['experience_id'] user_id = get_jwt_identity() about = experience_data['about'] experience = Experience.query.filter( Experience.id == experience_id ).first() user = User.get(user_id) if not experience: return { 'status': 'failed', 'message': 'experience not found' }, 400 if not experience.can_apply: return { 'status': 'failed', 'message': 'could not apply for experience, can_apply = false' }, 403 artist_slot_left = experience.artist_slot - len(experience.artist_applications) if artist_slot_left <= 0: return { 'status': 'error', 'message': 'not enough slot' }, 400 # save images to s3 images_url = [] if 'images' in experience_data: images = experience_data['images'] for image in images: image_ext = image.split(';base64')[0].replace('data:image/', '') image = image.split('base64,')[1] file = BytesIO(base64.b64decode(image)) filename = '{}.{}'.format(str(uuid.uuid4()), image_ext) is_save_image_success = save_file_in_s3_by_file('rodenia-images', file, filename) # if failed to upload just neglected it if is_save_image_success: images_url.append('https://rodenia-images.s3.us-east-2.amazonaws.com/{}'.format(filename)) try: admin = User.query.filter( User.role == 'admin' ).all() admin_emails = [a.email for a in admin] if admin_emails: is_multiple = False if len(admin_emails) > 1: is_multiple = True else: admin_emails = admin_emails[0] email_body = ApplyExperienceEmail.EMAIL_BODY.replace('{artist_name}', user.full_name)\ .replace('{experience_name}', experience.title) plain_email_body = ApplyExperienceEmail.PLAIN_EMAIL_BODY.replace('{artist_name}', user.full_name) \ .replace('{experience_name}', experience.title) send_email = send_plain_email( admin_emails, ApplyExperienceEmail.EMAIL_SUBJECT, plain_email_body, is_multiple, is_html=True, html_content=email_body ) log = { 'email_type': EmailTypes.APPLY_EXPERIENCE_EMAIL, 'user_id': user_id, 'email_from_name': None, 'email_to': str(admin_emails), 'email_subject': ApplyExperienceEmail.EMAIL_SUBJECT, 'email_body': email_body } if send_email: log['status_code'] = send_email['status_code'] log['message'] = send_email['body'] EmailLog.log_to_db(**log) except Exception as e: return { 'status': 'error', 'message': 'Failed to send in application to admin for approval. Please try again' }, 500 artist_application = ArtistExperienceApplication( experience_id=experience_id, user_id=user_id, images=images_url, about=about ) db.session.add(artist_application) try: db.session.commit() artist_application = ArtistExperienceApplicationSchema().dump(artist_application).data return { 'status': 'success', 'artist_application': artist_application }, 201 except Exception as e: db.session.rollback() return { 'status': 'error', 'message': 'failed record data to db' }, 422
def user_factory(i): return User(username="******".format(i), email="user{}@mail.com".format(i))
def post(self): request_data = request.json user = User.find_user_by_email(request_data['email']) if user: return { 'status': 'error', 'message': 'email already registered' }, 422 user = User(role='artist', status='pending', password=request_data['password']) for key, value in request_data.items(): if key != 'password' and key != 'image': setattr(user, key, value) if 'image' in request_data: image = request_data['image'] image_ext = image.split(';base64')[0].replace('data:image/', '') image_base64 = image.split('base64,') if len(image_base64) < 2: return { 'status': 'error', 'message': 'invalid image file' }, 400 image = image.split('base64,')[1] file = BytesIO(base64.b64decode(image)) filename = '{}.{}'.format(str(uuid.uuid4()), image_ext) is_save_image_success = save_file_in_s3_by_file( 'rodenia-images', file, filename) if not is_save_image_success: return { 'status': 'error', 'message': 'failed save to aws' }, 422 setattr( user, 'image', 'https://rodenia-images.s3.us-east-2.amazonaws.com/{}'.format( filename)) try: # get admins data admin = User.query.filter(User.role == 'admin').all() admin_emails = [a.email for a in admin] if admin_emails: is_multiple = False if len(admin_emails) > 1: is_multiple = True else: admin_emails = admin_emails[0] send_email = send_plain_email( admin_emails, NewSignedUpEmail.EMAIL_SUBJECT, NewSignedUpEmail.PLAIN_EMAIL_BODY, is_multiple, is_html=True, html_content=NewSignedUpEmail.EMAIL_BODY) log = { 'email_type': EmailTypes.NEW_SIGNED_UP_EMAIL, 'user_id': user.id, 'email_from_name': None, 'email_to': str(admin_emails), 'email_subject': NewSignedUpEmail.EMAIL_SUBJECT, 'email_body': NewSignedUpEmail.EMAIL_BODY } if send_email: log['status_code'] = send_email['status_code'] log['message'] = send_email['body'] EmailLog.log_to_db(**log) except Exception as e: return { 'status': 'error', 'message': 'Failed to send in application to admin for approval. Please try again' }, 500 db.session.add(user) try: db.session.commit() user_dump = UserSchema().dump(user).data user_dump.pop("password", None) user_dump.pop("email_logs", None) return {'status': 'success', 'user': user_dump}, 201 except Exception as e: print(str(e)) db.session.rollback() return { 'status': 'error', 'message': 'failed save to database' }, 422