Example #1
0
File: meal.py Project: mariajbp/LI4
    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
Example #2
0
File: user.py Project: mariajbp/LI4
    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
Example #3
0
File: auth.py Project: mariajbp/LI4
    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
Example #4
0
    def post(self):
        args = KioskAPI.parser_post.parse_args()
        target_id_user = get_jwt_identity()

        amount = args['amount']
        ticket_type = args['ticket_type']

        from binascii import hexlify

        price = 0.0
        try:
            price = TicketType.get_type(ticket_type).price
        except ErrorCodeException as ec:
            return error_code(ec), 500

        if amount > self.__MAX_TICKET_AMOUNT or amount <= 0:
            return error_message("Invalid amount MAX = " +
                                 str(__MAX_TICKET_AMOUNT)), 500

        order_id = gen_order(KioskAPI.__OAUTH_TOKEN, price * amount)

        if order_id == None:
            KioskAPI.__OAUTH_TOKEN = gen_oauth2_token(PP_USERNAME, PP_PASSWORD)
            order_id = gen_order(KioskAPI.__OAUTH_TOKEN, price * amount)
            print("Logged in")
            if order_id == None:
                return error_message("Something unexpected ocurred"), 500

        KioskAPI.awaiting_transactions[order_id] = {
            "amount": amount,
            "price": price,
            "ticket_type": ticket_type,
            "id_user": target_id_user
        }

        return {
            "transaction_status": "Payment",
            "total_price": price * amount,
            "id_transaction": order_id,
            "paypal_link": approve_link(order_id)
        }, 201
Example #5
0
File: meal.py Project: mariajbp/LI4
    def get(self):
        import datetime

        args = MealAPI.parser_get.parse_args()
        try:
            begin = datetime.date.today(
            ) if args['begin'] == None else datetime.date.fromisoformat(
                args['begin'])
            end = begin + datetime.timedelta(weeks=1) if args[
                'end'] == None else datetime.date.fromisoformat(args['end'])
        except:
            return error_message(
                "Invalid date format (ISO Date format required)!"), 400

        if begin > end:
            return error_message("begin bigger than end!"), 400

        try:
            id_meal_type = None
            if args['meal_type'] != None:
                id_meal_type = MealType.get_by_name(
                    args['meal_type']).id_meal_type
            id_location = None
            if args['location'] != None:
                id_location = Location.get_by_name(
                    args['location']).id_location
            if id_location != None or id_meal_type != None:
                print("here")
                return {
                    "meals": [
                        m.to_json() for m in Meal.get_between(
                            begin, end, id_meal_type, id_location)
                    ]
                }, 200
        except ErrorCodeException as ec:
            return error_code(ec), 400

        #print("or here here")
        return {
            "meals": [m.to_json() for m in Meal.get_between(begin, end)]
        }, 200
Example #6
0
File: auth.py Project: mariajbp/LI4
    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
Example #7
0
    def get(self):
        args = StatisticsAPI.parser_get.parse_args()

        sender_id_user = get_jwt_identity()

        today = datetime.date.today()
        today_minus_week = today - datetime.timedelta(weeks=-1)

        begin = datetime.date.fromisoformat(
            args['begin']) if args['begin'] != None else today_minus_week
        end = datetime.date.fromisoformat(
            args['end']) if args['end'] != None else today

        if begin > end:
            return error_message("Invalid dates interval!"), 400

        try:
            res = History.db.session.execute(
                'SELECT DATE(used_datetime) as used_date, is_lunch(TIME(used_datetime)) as is_lunch FROM History h WHERE DATE(h.used_datetime) > :begin AND DATE(h.used_datetime) < :end AND id_user = :id_user;',
                {
                    'begin': begin,
                    'end': end,
                    'id_user': sender_id_user
                })
            hmm = {}
            for row in res:
                ud = str(row['used_date'])
                if ud not in hmm:
                    hmm[ud] = {'lunch': 0, 'dinner': 0}

                if row['is_lunch']:
                    hmm[ud]['lunch'] += 1
                else:
                    hmm[ud]['dinner'] += 1

                print()
            return {"statistics": hmm}, 200
        except Exception as e:
            print(e)
            return error_message("Something unexpected occured!"), 500
Example #8
0
File: meal.py Project: mariajbp/LI4
    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
Example #9
0
    def patch(self):
        args = KioskAPI.parser_patch.parse_args()
        target_id_user = get_jwt_identity()

        id_transaction = args['id_transaction']

        if not id_transaction in KioskAPI.awaiting_transactions:
            return error_message("Invalid transaction identifier"), 500

        context = KioskAPI.awaiting_transactions[id_transaction]

        if context['id_user'] != target_id_user:
            return error_message("Forbidden"), 401

        if not capture_order(KioskAPI.__OAUTH_TOKEN, id_transaction):
            return {"transaction_status": "Payment"}, 200

        bought = []
        from binascii import hexlify
        try:
            total_price = context['price'] * context['amount']
            dtt_now = datetime.datetime.now()
            for i in range(context['amount']):
                tckt = Ticket(target_id_user, context['ticket_type'])
                #print(str(tckt.id_ticket))

                bought.append(hexlify(tckt.id_ticket).decode('ascii'))
                Ticket.add_ticket(tckt)
                Transaction.add_transaction(
                    Transaction(id_transaction, context['id_user'],
                                tckt.id_ticket, total_price, dtt_now))
        except ErrorCodeException as ec:
            return error_code(ec), 500
        except Exception as e:
            print(e)
            return error_message("Something unexpected occurred"), 500

        return {"transaction_status": "Success", "ticket_ids": bought}, 201


#########################################################################

#        args = KioskAPI.parser_post.parse_args()
#
#        target_id_user = get_jwt_identity()
#
#        amount = args['amount']
#        ticket_type = args['ticket_type']
#
#        from binascii import hexlify
#        bought = []
#
#        price = 0.0
#        try:
#            price = TicketType.get_type(ticket_type).price
#        except ErrorCodeException as ec:
#            return error_code(ec) , 500
#
#        if amount > self.__MAX_TICKET_AMOUNT or amount <= 0:
#            return error_message("Invalid amount MAX = " + str(__MAX_TICKET_AMOUNT)) , 500
#
#        try:
#            for i in range(amount):
#                tckt = Ticket(target_id_user,ticket_type)
#                #print(str(tckt.id_ticket))
#
#                bought.append(hexlify(tckt.id_ticket).decode('ascii'))
#                Ticket.add_ticket(tckt)
#        except ErrorCodeException as ec:
#            return error_code(ec) , 500
#        except :
#            return error_message("Something unexpected occurred") , 500
#
#
#        return {
#            "transaction_status" : "Success",
#            "price" : price*amount,
#            "ticket_ids" : bought
#            } , 200