示例#1
0
    def post(self):
        req_body = request.get_json()
        try:
            # load method from marshmallow validates data according to schema definition
            valid_data = user_schema.load(req_body)
        except ValidationError as err:
            return custom_json_response(err.messages, 400)

        if User.get_user_by_email(req_body['email']):
            return custom_json_response({
                "error": "User already exists. Please supply a different email."
            }, 400)

        new_user = User(**valid_data)
        new_user.save()

        access_token = create_access_token(
            identity={"id": new_user.id}, expires_delta=timedelta(days=30))

        refresh_token = create_refresh_token(
            identity={"id": new_user.id}, expires_delta=timedelta(days=30))

        response_data = {
            "message": "Created",
            "user": user_schema.dump(new_user)
        }
        response = custom_json_response(response_data, 201)

        set_access_cookies(response, access_token)
        set_refresh_cookies(response, refresh_token)

        return response
示例#2
0
def become_chef(
    meal,
    chef_cuisine,
    imageFile=None,
):
    try:
        meal_data = meal_item_schema.load(meal)
    except ValidationError as err:
        return custom_json_response(err.messages, 400)

    new_meal = MealItem(**meal_data)
    new_meal.save()

    if imageFile:
        s3_file_path = f'meal/{new_meal.id}/meal_pic'
        image_url = upload_picture(imageFile, s3_file_path)

        if not image_url:
            return custom_json_response(
                {"error": "Error with uploading image"}, 400)

        new_meal.update({'image': image_url})

    data = {
        "message": "Created",
        "meal": meal_item_schema.dump(new_meal),
        "chefCuisine": chef_cuisine
    }
    return custom_json_response(data, 200)
示例#3
0
    def post(self):
        req_body, email, password = None, None, None
        try:
            req_body = request.get_json()
            email = req_body['email']
            password = req_body['password']
        except Exception:
            data = {"message": "Please login with your email and password"}
            return custom_json_response(data, 400)

        user = User.authenticate(email, password)

        if user:
            access_token = create_access_token(
                identity={"id": user.id}, expires_delta=timedelta(days=30))
            refresh_token = create_refresh_token(
                identity={"id": user.id}, expires_delta=timedelta(days=30))
            response = custom_json_response(
                {
                    "message": "Authenticated",
                    'user': user_schema.dump(user)
                }, 200)

            set_access_cookies(response, access_token)
            set_refresh_cookies(response, refresh_token)
            return response
        else:
            data = {"message": "Incorrect username or password."}
            return custom_json_response(data, 401)
 def get(self, id=None):
     q_params = request.args
     if id:
         meal = MealItem.get_by_id(id)
         return meal_item_schema.dump(meal)
     if q_params.get("chefId"):
         meals = MealItem.get_meals_by_userId(q_params.get("chefId"))
         data = meal_item_schema.dump(meals, many=True)
         return custom_json_response(data, 200)
     meals = MealItem.get_all_meals()
     data = meal_item_schema.dump(meals, many=True)
     return custom_json_response(data, 200)
示例#5
0
    def post(self):
        try:
            data = json.loads(request.data)

            chef_id = data.get("chefId")
            user_id = data.get("userId")
            arrival_ts = data.get("arrivalDateTimeStamp")
            # items with meal_id and quantity
            ordered_items = data.get("orderedItems")

            order = Order(chef_id, user_id, arrival_ts)
            order.save()

            for item in ordered_items:
                ojmt_obj = OrderJoinMealItem(order.id, item.get("id"),
                                             item.get("quantity"))
                ojmt_obj.save()

            total_amount_dollars = compute_total(ordered_items)

            intent = stripe.PaymentIntent.create(amount=int(
                total_amount_dollars * 100),
                                                 currency='usd')

            return jsonify({
                'clientSecret': intent['client_secret'],
                'totalAmount': total_amount_dollars,
                'orderId': order.id
            })

        except Exception:
            return custom_json_response(
                {'error': 'problem getting clientSecret'}, 403)
 def put(self):
     user_id = get_jwt_identity().get('id')
     all_notifications = Notification.mark_all_as_read(user_id)
     data = {
         "message": "Notifications received",
         "notifications": notifications_schema.dump(all_notifications)
     }
     return custom_json_response(data, 200)
示例#7
0
    def put(self, id):
        req_body = request.get_json()
        order = Order.get_by_id(id)
        order.fulfill(req_body.get("clientSecret"))

        notifyUser(order.chefId, f'User {order.userId} has sent you an order')

        return custom_json_response({"message": "order created"}, 201)
示例#8
0
    def get(self):
        user_id = get_jwt_identity().get("id")
        curr_user = User.get_by_id(user_id)
        response = custom_json_response({'user': user_schema.dump(curr_user)},
                                        200)

        refresh_token = create_refresh_token(identity={"id": user_id},
                                             expires_delta=timedelta(days=30))
        set_refresh_cookies(response, refresh_token)

        return response
    def put(self, id):
        user_id = get_jwt_identity().get("id")

        meal_item = MealItem.get_by_id(id)
        if not meal_item or meal_item.userId != user_id:
            return custom_json_response(
                {"message": "You do not own that meal"}, 400)

        meal = request.form.to_dict()
        req_image = request.files.get('image')
        return edit_meal(meal, meal_item, req_image)
示例#10
0
    def put(self):
        current_userid = get_jwt_identity().get('id')
        req_body = request.form.to_dict()

        # convert cuisines from stringified json list to a python list
        if req_body.get('cuisines') and isinstance(req_body['cuisines'], str):
            req_body['cuisines'] = json.loads(req_body['cuisines'])

        req_image = request.files.get('profileImage')

        if req_image:
            s3_file_path = f'users/{current_userid}/profile_pic'
            profile_image_url = upload_picture(req_image, s3_file_path)

            if not profile_image_url:
                return custom_json_response({"error": "Error with uploading image"}, 400)

            req_body['profileImage'] = profile_image_url

        if req_body.get('email'):
            return custom_json_response({
                "error": "Cannot use this route to update email address."
            }, 403)

        try:
            valid_data = user_schema.load(req_body, partial=True)

        except ValidationError as err:
            return custom_json_response(err.messages, 400)

        user = User.get_by_id(current_userid)

        user.update(valid_data)
        data = {
            "user": user_schema.dump(user),
            "message": "Succesfully Edited."
        }
        return custom_json_response(data, 200)
示例#11
0
def edit_meal(edited_meal, meal_item, imageFile=None):
    if imageFile:
        s3_file_path = f'meal/{meal_item.id}/meal_pic'
        image_url = upload_picture(imageFile, s3_file_path)

        if not image_url:
            return custom_json_response(
                {"error": "Error with uploading image"}, 400)

        edited_meal['image'] = image_url
    try:
        valid_data = meal_item_schema.load(edited_meal, partial=True)
    except ValidationError as err:
        return custom_json_response(err.messages, 400)

    # prevent userId from being edited
    valid_data.pop("userId", None)
    meal_item.update(valid_data)
    data = {
        "meal": meal_item_schema.dump(meal_item),
        "message": "Succesfully Edited."
    }
    return custom_json_response(data, 200)
示例#12
0
    def get(self, id=None):
        q_params = request.args
        if id:
            user = User.get_by_id(id)
            return user_schema_private.dump(user)

        applied_filters = []
        sql_filters = []

        if q_params.get("userCuisines"):
            chosen_cuisines = q_params.get("userCuisines").split(",")
            applied_filters.append("cuisine")
            for c in chosen_cuisines:
                sql_filters.append(User.chefCuisine == c)

        chefs = User.query.filter(or_(*sql_filters)).all()
        ser_chefs = user_schema_private.dump(chefs, many=True)

        # supply maxDistance, userLat, and userLong to filter by distance
        if (q_params.get("maxDistance") and q_params.get("userLat")
                and q_params.get("userLon")):
            user_loc = (float(q_params.get("userLat")),
                        float(q_params.get("userLon")))
            max_dist = float(q_params.get("maxDistance"))
            applied_filters.append("distance")
            ser_chefs = [
                chef for chef in ser_chefs
                if chef.get("latitude") and chef.get("longitude") and distance(
                    (chef.get("latitude"),
                     chef.get("longitude")), user_loc) < max_dist
            ]

        data = {
            "results": ser_chefs,
            "Applied Filters": ",".join(applied_filters)
        }
        return custom_json_response(data, 200)
示例#13
0
 def get(self):
     # Returns all cuisines
     all_cuisines = Cuisine.query.all()
     ser_cuisines = cuisines_schema.dump(all_cuisines)
     return custom_json_response(ser_cuisines, 200)