Exemplo n.º 1
0
Arquivo: user.py Projeto: mariajbp/LI4
    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)
Exemplo n.º 2
0
Arquivo: auth.py Projeto: 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
Exemplo n.º 3
0
Arquivo: user.py Projeto: 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
Exemplo n.º 4
0
Arquivo: meal.py Projeto: 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
Exemplo n.º 5
0
Arquivo: auth.py Projeto: mariajbp/LI4
    def post(self):
        auth = request.authorization

        #generate_password_hash("epah_mas_que_chatice")

        if not auth or not auth.username or not auth.password:
            return make_response(
                unauthorized("Fields not specified"), 401,
                {'WWW-Authenticate': 'Basic realm="Login required!"'})

        try:
            user = User.get_user(auth.username)
        except ErrorCodeException as ec:
            return error_code(ec), 401, {
                'WWW-Authenticate': 'Basic realm="Login required!"'
            }

        #if not user:
        #    return make_response(error_code(ErrorCode.USER_DOESNT_EXISTS) , 401 , {'WWW-Authenticate' : 'Basic realm="Login required!"'})

        if user.check_password(auth.password):
            token = create_access_token(
                identity=str(user.id_user),
                user_claims={"permissions": user.permissions},
                expires_delta=datetime.timedelta(weeks=20))

            decoded_token = decode_token(token)
            added = SessionTable.add(
                user.id_user, decoded_token['jti'],
                datetime.datetime.fromtimestamp(decoded_token['exp'])
            )  # Old code #token = jwt.encode({'id_user' : auth.username, 'exp' : datetime.datetime.utcnow() + datetime.timedelta(minutes=5)}, app.config['TOKEN_GEN_KEY'])
            #print("Sessions:",SessionTable.size(user.id_user))

            if added:
                return make_response(jsonify({'token': token}), 200)
            else:
                return make_response(
                    unauthorized("Unable to login"), 401,
                    {'WWW-Authenticate': 'Basic realm="Login required!"'})

        return make_response(
            error_code(ErrorCode.WRONG_PASSWORD), 401,
            {'WWW-Authenticate': 'Basic realm="Login required!"'})
Exemplo n.º 6
0
Arquivo: user.py Projeto: mariajbp/LI4
    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)
Exemplo n.º 7
0
Arquivo: user.py Projeto: mariajbp/LI4
    def get(self, id_user):
        sender_user = User.get_user(get_jwt_identity())

        # Check permissions for listing other users rather than himself
        if (not sender_user.check_permission(
                Permissions.ADMIN)) and (not id_user == sender_user.id_user):
            return forbidden(), 403

        try:
            return {"user": User.get_user(id_user).to_json()}
        except ErrorCodeException as ec:
            return error_code(ec)
Exemplo n.º 8
0
    def get(self, id_user):

        sender_id_user = get_jwt_identity()
        if sender_id_user != id_user:
            return unauthorized("Forbiden!"), 403
        try:
            user_hist = History.get_all(id_user)
            return {
                "history":
                [he.to_json() for he in user_hist] if user_hist else []
            }, 200
        except ErrorCodeException as ec:
            return error_code(ec), 500
Exemplo n.º 9
0
Arquivo: meal.py Projeto: 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
Exemplo n.º 10
0
    def get(self):
        args = TicketTypeAPI.parser.parse_args()

        target_ticket_type = args['ticket_type']

        # Checks if ticket_type has been specified
        if target_ticket_type != None:
            try:
                return {
                    "ticket_type":
                    TicketType.get_type(target_ticket_type).to_json()
                }
            except ErrorCodeException as ec:
                return error_code(ec)

        else:
            return {
                "ticket_types": [tt.to_json() for tt in TicketType.get_all()]
            }
Exemplo n.º 11
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
Exemplo n.º 12
0
Arquivo: meal.py Projeto: 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
Exemplo n.º 13
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