def delete_application_messages(current_user): if not current_user.application: current_user.application = Application() for message in current_user.application.messages: db.session.delete(message) current_user.application.messages = [] db.session.commit() return create_response( {'messages': 'All messages removed from application state!'}, 200, '*')
def get_application_products(current_user): if not current_user.application: current_user.application = Application() data = [] for cart_assoc in current_user.application.cart: product_data = cart_assoc.product.data() product_data['count'] = cart_assoc.count data.append(product_data) return create_response({'products': data}, 200, '*')
def verify_user(): # Performs a POST request to verify a user try: json = request.json username = json["username"] password = json["password"] query = "SELECT * FROM user_by_username WHERE username = '******';".format( username) result = session.execute(query) for entry in result: if check_password_hash(entry.password, password): return create_response("User Verfied", 200) else: return create_response("User not verfied", 404) return create_response("User not found", 404) except (KeyError, AttributeError, TypeError): return create_response("Bad request with improper/incomplete fields", 403) except Exception: return create_response("Internal Server Error", 500)
def add_user(): # Performs a POST request to add a user try: json = request.json print(json) username = json["username"] password = generate_password_hash(json["password"]) if present(username): return create_response( "User with provided username already exists", 401) query = "INSERT INTO user_by_username (id, username, password) VALUES (uuid(), '{}', '{}');".format( username, password) print(query) session.execute(query) return create_response("User added successfully", 201) except (AttributeError, KeyError, TypeError): return create_response("Bad request with improper/incomplete fields", 403) except Exception: return create_response("Internal server serror", 500)
def add_poll(): # Performs a POST request for adding a poll try: json = request.json username = json["username"] title = json["title"] options = json["options"] votes = json["votes"] if present(username, title): return create_response("Poll with provided username and title already exists", 401) query = "INSERT INTO poll_by_username_and_title (username, title, id, options, votes) " query = query + "VALUES ('{}', '{}', uuid(), {}, {});".format(username, title, options, votes) session.execute(query) return create_response("Poll Successfully added", 201) except (KeyError, AttributeError, TypeError): return create_response("Bad request with improper/incomplete fields", 403) except Exception: return create_response("Internal Server Error", 500)
def get_products(): args = {} category = request.args.get('category', None) tags = request.args.get('tags', "").split(",") if category: args['category_title'] = category products = Product.query.filter_by(**args).all() for tag in tags: if tag != '': products = [ product for product in products if tag in [product_tag.value for product_tag in product.tags] ] return create_response( {'products': [product.data() for product in products]}, 200, '*')
def create_user(): try: data = request.get_json() if not data: return create_response({'message': 'No data provided!'}, 400, '*') print(data) missing = [] for field in ['username', 'password']: if field not in data.keys(): missing.append(field) elif data[field] == None or len(str(data[field])) < 5: return create_response( { 'message': 'Field {0} must be 5 characters or longer.'.format( field) }, 400, '*') if len(missing) > 0: return create_response( {'message': 'Missing required fields: ' + ', '.join(missing)}, 400, '*') user = User.query.filter_by(username=data['username']).first() if user: return create_response({'message': 'Username already taken!'}, 409, '*') hashed_password = generate_password_hash(data['password'], method='sha256') user = User(username=data['username'], password=hashed_password, first_name=data.get('firstName', None), last_name=data.get('lastName', None), goal_daily_calories=data.get('goalDailyCalories', None), goal_daily_carbohydrates=data.get('goalDailyCarbohydrates', None), goal_daily_protein=data.get('goalDailyProtein', None), goal_daily_fat=data.get('goalDailyFat', None), goal_daily_activity=data.get('goalDailyActivity', None), admin=False) user.application = Application() db.session.add(user) db.session.commit() return create_response({'message': 'User created!'}, 200, '*') except Exception as e: return create_response({'message': str(e)}, 500, '*')
def modify_application(current_user): if not current_user.application: current_user.application = Application() data = request.get_json() if 'page' in data.keys(): current_user.application.page = data['page'] if 'back' in data.keys(): current_user.application.back = data['back'] if 'dialogflowUpdated' in data.keys(): current_user.application.dialogflow_updated = data['dialogflowUpdated'] else: current_user.application.dialogflow_updated = True db.session.commit() return create_response({'message': 'Application state modified!'}, 200, '*')
def create_meal(current_user): data = request.get_json() try: name = data['name'] except: name = None try: date = date_parse(data['date']) except: date = None new_meal = Meal(name=name, date=date, user_id=current_user.id) db.session.add(new_meal) db.session.commit() return create_response({ 'message': 'Meal created!', 'id': new_meal.id }, 200, '*')
def add_quota_used(self, quota_info, content_uploaded): quota_limit = long(quota_info['quota_limit']) quota_used = long(quota_info['quota_used']) quota_used_afer_put = quota_used + long(content_uploaded) quota_used_after_put = quota_used + content_uploaded if quota_used_after_put > quota_limit: self.app.logger.error("StackSync Quota: Quota exceeded. Available space: "+str(quota_limit-quota_used)) return create_error_response(413, 'Upload exceeds quota.') #Notify quota_server for the new quota_used value. self.app.logger.info('StackSync Quota: add_quota_used') response = self.rpc_server.XmlRpcQuotaHandler.updateAvailableQuota(quota_info['user'], str(quota_used_after_put)) response = create_response(response, status_code=200) if not is_valid_status(response.status_int): self.app.logger.error("StackSync Quota: Error updating quota used") return response return self.app
def __call__(self, req): self.app.logger.info('StackSync Quota start') self.app.logger.info(req.environ) #Check if is a call to object _, _, container, swift_object = split_path(req.path, 0, 4, True) if not swift_object: return self.app #check if is an authorize reqeuest container_info = get_container_info(req.environ, self.app, swift_source='CQ') response = self.authorize(req, container_info) if response: return response #check if is a valid request if not self.valid_request(req): # We only want to process PUT and DELETE requests return self.app quota_info = self.rpc_server.XmlRpcQuotaHandler.getAvailableQuota(container) response = create_response(quota_info, status_code=200) if not is_valid_status(response.status_int): if response.status_int == 404: # User not found. No StackSync user return self.app else: self.app.logger.error("StackSync Quota: status code: %s. body: %s", str(response.status_int), str(response.body)) return response quota_info = json.loads(quota_info) if req.method == 'PUT': return self.add_quota_used(quota_info, long(req.environ["CONTENT_LENGTH"])) if req.method == 'DELETE': return self.subtract_quota_used(quota_info, req.environ)
def create_application_message(current_user): if not current_user.application: current_user.application = Application() data = request.get_json() try: date = date_parse(data['date']) except: date = None new_message = Message(date=date, application_id=current_user.application.id, is_user=data.get('isUser', None), text=data.get('text', None)) db.session.add(new_message) current_user.application.messages.append(new_message) db.session.commit() return create_response( { 'message': 'Message created!', 'id': new_message.id }, 200, '*')
def subtract_quota_used(self, quota_info, env): # HEAD to swift resource to know the content length quota_limit = long(quota_info['quota_limit']) quota_used = long(quota_info['quota_used']) object_info = get_object_info(env, self.app, env['PATH_INFO']) if not object_info or not object_info['length']: content_to_delete = 0 else: content_to_delete = long(object_info['length']) quota_used_after_delete = quota_used - content_to_delete #send new quota to quota server self.app.logger.info('StackSync Quota: subtract_quota_used') response = self.rpc_server.XmlRpcQuotaHandler.updateAvailableQuota(quota_info['user'], str(quota_used_after_delete)) response = create_response(response, status_code=200) if not is_valid_status(response.status_int): self.app.logger.error("StackSync Quota: Error updating quota used") return response return self.app
def get_tags(): tags = Tag.query.all() return create_response({'tags' : [tag.data() for tag in tags]},200,'*')
def get_product_reviews(product_id): product = Product.query.filter_by(id=product_id).first() if not product: return create_response({'message':'Product not found!'},404,'*') return create_response({'reviews':[review.data() for review in product.reviews]},200,'*')
def get_meals(current_user): meals = Meal.query.filter_by(user_id=current_user.id).all() return create_response({'meals': [meal.data() for meal in meals]}, 200, '*')
def get_food_archetypes(): foods = FoodArchetype.query.all() return create_response({'foods' : [food.data() for food in foods]},200,'*')
def get_product(product_id): product = Product.query.filter_by(id=product_id).first() if not product: return create_response({'message': 'Product not found!'}, 404, '*') return create_response(product.data(), 200, '*')
def get_categories(): categories = Category.query.all() return create_response( {'categories': [category.data() for category in categories]}, 200, '*')
def get_application(current_user): return create_response(current_user.application.data(), 200, '*')