Пример #1
0
    def post(self):
        import datetime

        body = request.json
        if not body:
            return {"error": "No json body found on request"}

        # Request body argument validation
        date = None
        try:
            date = datetime.date.fromisoformat(body['date'])
        except:
            return error_message(
                "Invalid date format (ISO Date format required)!"), 400

        try:
            id_meal_type = MealType.get_by_name(body['meal_type']).id_meal_type
            id_location = Location.get_by_name(body['location']).id_location
            try:
                Meal.add_meal(
                    Meal(date, id_location, id_meal_type, body['soup'],
                         body['main_dish'], body['description']))
                return success()
            except KeyError:
                return error_message("Missing arguments!"), 400
            #except MySQLdb._exceptions.DataError:
            #    return error_message("Invalid argument length!") , 400
            except Exception as e:
                return error_message("Something unexpected occured!"), 500

        except ErrorCodeException as ec:
            return error_code(ec), 400
Пример #2
0
def update_user(request, user_id):
    if request.method == "PUT":
        data = json.loads(request.body.decode('utf-8'))
        errors = views.validate(
            data, {
                "name": "NNULL|TYPEstr",
                "user_type": "NNULL|TYPEstr",
                "latitude": "NNULL",
                "longitude": "NNULL"
            })
        if errors:
            return responses.invalid(errors)
        user = User.objects.filter(id=user_id).all()
        if not user:
            return responses.invalid("Invalid user id")
        User.objects.filter(id=user_id).update(name=data["name"],
                                               user_type=data["user_type"],
                                               latitude=data["latitude"],
                                               longitude=data["longitude"])
        return responses.success({
            "id": user[0].id,
            "name": data["name"],
            "user_type": data["user_type"],
            "latitude": data["latitude"],
            "longitude": data["longitude"],
            "phone": user[0].phone
        })
    return responses.invalid("Invalid method type")
Пример #3
0
    def put(self):
        sender_id_user = get_jwt_identity()
        args = UserAPI.parser_put.parse_args()

        target_id_user = args['id_user']
        old_password = args['old_password']
        new_password = args['new_password']

        if old_password != None and new_password != None:
            try:
                u = User.get_user(target_id_user)
                tmp = User.get_user(sender_id_user)
                if sender_id_user != target_id_user and not tmp.check_permission(
                        Permissions.ADMIN):
                    return forbidden(), 403
                else:
                    if u.check_password(old_password):
                        u.set_password(new_password)
                        return success()
                    else:
                        return error_message("Incorrect old password!"), 500
            except ErrorCodeException as ec:
                return error_code(ec), 500
        else:
            return error_message("Argument required"), 401
Пример #4
0
    def post(self):
        args = RegisterAPI.parser_post.parse_args()

        id_user = args['id_user']
        name = args['name']
        password = args['password']
        email = args['email']

        if not (id_user and name and password and email):
            return error_message("Insuficient arguments"), 400

        ################## Input Validation ##################
        from common.utils import params_validation, VALID_ID_USER_REGEX, VALID_NAME_REGEX, VALID_PASSWORD_REGEX, VALID_EMAIL_REGEX

        params = [id_user, name, password, email]
        rgxs = [
            VALID_ID_USER_REGEX, VALID_NAME_REGEX, VALID_PASSWORD_REGEX,
            VALID_EMAIL_REGEX
        ]

        try:
            params_validation(rgxs, params)
        except ErrorCodeException as ec:
            return error_code(ec), 400
        ######################################################

        try:
            User.add_user(
                User(id_user, email, password, name, Permissions.USER))
            return success(), 200
        except ErrorCodeException as ec:
            return error_code(ec), 400
Пример #5
0
    def post(self):
        body = request.json
        if not body:
            return {"error": "No json body found on request"}

        id_user = body['id_user']
        email = body['email']
        password = body['password']
        name = body['name']

        ################## Input Validation ##################
        from common.utils import params_validation, VALID_ID_USER_REGEX, VALID_NAME_REGEX, VALID_PASSWORD_REGEX, VALID_EMAIL_REGEX

        params = [id_user, name, password, email]
        rgxs = [
            VALID_ID_USER_REGEX, VALID_NAME_REGEX, VALID_PASSWORD_REGEX,
            VALID_EMAIL_REGEX
        ]

        try:
            params_validation(rgxs, params)
        except ErrorCodeException as ec:
            return error_code(ec), 400
        ######################################################

        try:
            User.add_user(
                User(body['id_user'], body['email'], body['password'],
                     body['name'], int(body['permissions'])))
            return success()
        except ErrorCodeException as ec:
            return error_code(ec)
Пример #6
0
def get_product_type(request):
    if request.method == "GET":
        prod_type = ProductType.objects.all()
        result = []
        for pt in prod_type:
            result.append({"id": pt.id, "name": pt.name})
        return responses.success(result)
    return responses.invalid("Invalid method type")
Пример #7
0
def get_user(request, user_id=None):
    if request.method == "GET":
        if user_id is not None and not user_id == "":
            user = User.objects.filter(id=user_id).all()
        else:
            user = User.objects.all()
        return responses.success(response_object(user, user_id))
    return responses.invalid("Invalid method type")
Пример #8
0
def post(request):
    try:
        if request.method == "POST":
            data = json.loads(request.body.decode('utf-8'))
            # errors = views.validate(data, {"name": "NNULL|TYPEstr", "description": "NNULL|TYPEstr",
            #                                "product_type": "NNULL|TYPEstr",
            #                                "latitude": "NNULL", "longitude": "NNULL",
            #                                "location": "NNULL|TYPEstr", "image": "NNULL|TYPEstr",
            #                                "user_id": "NNULL|TYPEint", "price": "NNULL"})
            # if errors:
            #     return responses.invalid(errors)
            User.objects.get(id=data["user_id"])
            product_type = data["product_type"]
            product = ProductType.objects.filter(id=product_type)
            if not product:
                return responses.invalid("Invalid Product Type")
            product_name = product[0].name
            try:
                latitude = data["latitude"]
            except KeyError:
                latitude = 0.000
            try:
                longitude = data["longitude"]
            except KeyError:
                longitude = 0.000
            try:
                location = data["location"]
            except KeyError:
                location = ""
            try:
                image = data["image"]
            except KeyError:
                image = ""
            prod = Product.objects.create(name=data["name"],
                                          description=data["description"],
                                          product_type=product[0],
                                          longitude=longitude,
                                          latitude=latitude,
                                          location=location,
                                          image=image,
                                          user_id=data["user_id"],
                                          price=data["price"])
            return responses.success({
                "id": prod.id,
                "name": prod.name,
                "description": prod.description,
                "product_type": product_name,
                "longitude": prod.longitude,
                "latitude": prod.latitude,
                "location": prod.location,
                "image": prod.image,
                "price": prod.price,
                "user_id": prod.user_id,
                "status": prod.status
            })
        return responses.invalid("Invalid method type")
    except User.DoesNotExist:
        return responses.invalid("Invalid user id")
Пример #9
0
    def delete(self):
        args = UserAPI.parser_del.parse_args()
        id_user = args['id_user']

        if not id_user:
            return {"error": "Argument required"}

        try:
            User.delete(id_user)
            return success()
        except ErrorCodeException as ec:
            return error_code(ec)
Пример #10
0
    def post(self):
        decoded_token = get_raw_jwt()
        token_id = decoded_token['jti']
        sender_id_user = get_jwt_identity()  # or # decoded_token['identity']

        torf = SessionTable.remove(sender_id_user, token_id)
        #print("Removed? ",torf)
        #print("Sessions:",SessionTable.size(sender_id_user))
        if torf:
            return success("Logged out successfully"), 200
        else:
            return error_message("Could not loggout"), 500
Пример #11
0
def patch(request, prod_id=None):
    if request.method == "PATCH":
        data = json.loads(request.body.decode('utf-8'))
        if prod_id is None and not prod_id == " ":
            return responses.invalid("Please provide id")
        prod = Product.objects.filter(id=prod_id)
        if not prod:
            return responses.invalid("Invalid product id")
        for key in data.keys():
            if key == "status":
                Product.objects.filter(id=prod_id).update(
                    status=data["status"])
        return responses.success("")
    return responses.invalid("Invalid method type")
Пример #12
0
def get(request, prod_id=None):
    if request.method == "GET":
        if prod_id is not None and not prod_id == "":
            product = Product.objects.filter(id=prod_id).all()
        else:
            created_by = request.GET.get("created_by", None)
            if created_by is None or created_by == "":
                product = Product.objects.select_related('product_type').filter(status="fresh").\
                    order_by('-created_at').all()
            else:
                product = Product.objects.select_related('product_type').\
                    filter(user_id=created_by).order_by('-created_at').all()
        return responses.success(response_object(product, prod_id))
    return responses.invalid("Invalid method type")
Пример #13
0
    def delete(self):
        args = MealAPI.parser_del.parse_args()
        date = args['date']
        location = args['location']
        meal_type = args['meal_type']

        if not (date and meal_type and location):
            return error_message("Arguments required"), 400

        try:
            id_location = Location.get_by_name(location).id_location
            id_meal_type = MealType.get_by_name(meal_type).id_meal_type
            Meal.delete(date, id_location, id_meal_type)

            return success()
        except ErrorCodeException as ec:
            return error_code(ec), 400
Пример #14
0
def login(request):
    data = json.loads(request.body.decode('utf-8'))
    errors = views.validate(data, {"phone": "NNULL|TYPEstr"})
    if errors:
        return responses.invalid(errors)
    user = User.objects.filter(phone=data["phone"])
    if user:
        user = User.objects.get(phone=data["phone"])
        is_profile_complete = True
    else:
        user = User.objects.create(phone=data["phone"])
        is_profile_complete = False
    content = {
        "user_id": user.id,
        "name": user.name,
        "is_profile_complete": is_profile_complete
    }
    return responses.success(content)
Пример #15
0
def add_product_type(request):
    if request.method == "POST":
        data = json.loads(request.body.decode('utf-8'))
        prod_type = ProductType.objects.create(name=data["name"])
        return responses.success({"id": prod_type.id})
    return responses.invalid("Invalid method type")
Пример #16
0
def get_merchants(request):
    if request.method == "GET":
        user = User.objects.filter(
            Q(user_type="Trader") | Q(user_type="trader")).all()
        return responses.success(response_object(user))
    return responses.invalid("Invalid method type")
Пример #17
0
def delete(request, prod_id=None):
    if request.method == "DELETE":
        Product.objects.filter(id=prod_id).delete()
        return responses.success("")
    return responses.invalid("Invalid method type")