Exemple #1
0
    def post(self):
        print(request.json)
        logger.getLogger().debug("POST at /users/logout")
        logger.getLogger().debug(request.json)

        if not "UserToken" in request.headers:
            return ResponseMaker.response_error(constants.PARAMERR,
                                                "Bad request - missing token")
        token = request.headers['UserToken']

        result = TokenGenerator.validateToken(token)

        # (mongodb) Return all logged in users.
        users_online = MongoController.getCollection("online")

        user = [
            User.UserJSON(user) for user in users_online.find()
            if (user['username'] == result[1]['username'])
        ]

        if (len(user) == 0):
            return ResponseMaker.response_error(constants.NOT_FOUND,
                                                "User not found")

        #users_online.delete_many(user[0]);
        users_online.update({"_id": user[0]["_id"]},
                            {"$set": {
                                "online": False
                            }})

        return ResponseMaker.response_object(constants.SUCCESS, ['user'],
                                             [user[0]])
Exemple #2
0
    def delete(self, id):
        print("DELETE at /users/id")
        logger.getLogger().debug("DELETE at /users/" + str(id))

        if not "UserToken" in request.headers:
            return ResponseMaker.response_error(constants.PARAMERR,
                                                "Bad request - missing token")

        token = request.headers['UserToken']

        (valid, decoded) = TokenGenerator.validateToken(token)

        print(decoded)
        if not valid or (decoded['_id'] != id):
            return ResponseMaker.response_error(constants.FORBIDDEN,
                                                "Forbidden")

        #Ask Shared-Server to delete this user
        delete_success, status_code = ServerRequest.deleteUser(id)
        if delete_success:
            #Delete in local data-base
            candidates = [
                User.UserJSON(user) for user in self.users.find()
                if user['_id'] == id
            ]
            self.users.delete_many({"_id": id})
            logger.getLogger().info("Successfully deleted user.")
        else:
            logger.getLogger().error(
                "Attempted to delete user with non-existent id.")
            return ResponseMaker.response_error(status_code, "Delete error")

        return ResponseMaker.response_object(constants.DELETE_SUCCESS,
                                             ['user'], candidates)
Exemple #3
0
    def get(self, id):
        logger.getLogger().debug("GET at /users/" + str(id))
        if not "UserToken" in request.headers:
            return ResponseMaker.response_error(constants.PARAMERR,
                                                "Bad request - missing token")

        token = request.headers['UserToken']

        (valid, decoded) = TokenGenerator.validateToken(token)

        print("GET at /user/id")
        candidates = [user for user in self.users.find() if user['_id'] == id]

        if len(candidates) == 0:
            #If not available in local data-base, ask Shared-Server for user info.
            (status, response) = ServerRequest.getUser(id)

            if (status != constants.SUCCESS):
                return ResponseMaker.response_error(status,
                                                    response["message"])

            candidates = [response]
            user = candidates[0]
            self.users.insert_one(user)

        if len(candidates) == 0:
            logger.getLogger().error(
                "Attempted to retrieve user with non-existent id.")
            return ResponseMaker.response_error(constants.NOT_FOUND,
                                                "User id not found:" + str(e))

        return ResponseMaker.response_object(constants.SUCCESS, ['user'],
                                             [User.UserJSON(candidates[0])])
Exemple #4
0
    def get(self, id):
        logger.getLogger().debug("GET at /users/userId/cars " + str(id))
        if not "UserToken" in request.headers:
            return ResponseMaker.response_error(constants.PARAMERR,
                                                "Bad request - missing token")

        token = request.headers['UserToken']

        (valid, decoded) = TokenGenerator.validateToken(token)

        print(decoded)
        if not valid or (decoded['_id'] != id):
            return ResponseMaker.response_error(constants.FORBIDDEN,
                                                "Forbidden")

        cars = [
            user for user in self.users.find()
            if user['_id'] == id and user['type'] == 'driver'
        ]

        try:
            if (len(cars) == 0):
                print("FETECHING CARS...")
                status_code, cars = ServerRequest.getUserCars(id)
        except Exception as e:
            return ResponseMaker.response_error(
                constants.NOT_FOUND,
                "User id did not match any existing users.")
        return ResponseMaker.response_object(constants.SUCCESS, ['cars'], cars)
Exemple #5
0
    def get(self, id):
        logger.getLogger().debug("GET at /trips/" + str(id))

        # (validate-token) Validate user token
        if not "UserToken" in request.headers:
            return ResponseMaker.response_error(constants.PARAMERR,
                                                "Bad request - missing token")

        token = request.headers['UserToken']
        (valid, response) = TokenGenerator.validateToken(token)

        if not valid:
            return ResponseMaker.response_error(constants.UNAUTHORIZED,
                                                "Unauthorized")

        active_trips = MongoController.getCollection("active_trips")
        trip = list(active_trips.find({"_id": id}))

        if len(trip) == 0:
            return ResponseMaker.response_error(constants.NOT_FOUND,
                                                "Not found")

        # This should never happen
        if len(trip) > 1:
            return ResponseMaker.response_error(
                constants.ERROR,
                "Internal server error - more than one trip with same ID")

        trip = trip[0]
        print(trip)

        return ResponseMaker.response_object(constants.SUCCESS,
                                             ["message", "trip"], ["OK", trip])
Exemple #6
0
    def get(self, userId, carId):
        logger.getLogger().debug("GET at /users/" + str(userId) + "/carId/" +
                                 str(carId))
        if not "UserToken" in request.headers:
            return ResponseMaker.response_error(constants.PARAMERR,
                                                "Bad request - missing token")

        token = request.headers['UserToken']

        (valid, decoded) = TokenGenerator.validateToken(token)

        print(decoded)
        if not valid or (decoded['_id'] != userId):
            return ResponseMaker.response_error(constants.FORBIDDEN,
                                                "Forbidden")

        car = [
        ]  #[ car for car in self.users.find( { $and: [ { "_id": { $eq : userId} }, { "cars._id": { $eq : carId } } ] } , { cars : 1 } ) if car["_id"]==carId ]

        try:
            if (len(car) == 0):
                status_code, car = ServerRequest.getUserCar(userId, carId)
            return ResponseMaker.response_object(constants.SUCCESS, ['car'],
                                                 car["properties"])
        except Exception as e:
            return ResponseMaker.response_error(constants.ERROR,
                                                "Unexpected error")
Exemple #7
0
    def post(self):
        print(request.json)
        logger.getLogger().debug("POST at /trips/estimation")
        logger.getLogger().debug(request.json)

        try:
            # (validate-token) Validate user token
            if not "UserToken" in request.headers:
                return ResponseMaker.response_error(
                    constants.PARAMERR, "Bad request - missing token")

            token = request.headers['UserToken']

            (valid, response) = TokenGenerator.validateToken(token)
            if not valid:
                return ResponseMaker.response_error(constants.FORBIDDEN,
                                                    "Forbidden")

            #Send trip estimation request to shared server.
            (status, response) = ServerRequest.estimateTrip(request.json)

            if (status != constants.SUCCESS):
                return ResponseMaker.response_error(status,
                                                    response["message"])

            return ResponseMaker.response_object(status, ["cost"], [response])
        except Exception as e:
            logger.getLogger().error("Error " + str(e))
            return ResponseMaker.response_error(constants.ERROR,
                                                "Unexpected error" + str(e))
Exemple #8
0
	def post(self):
		logger.getLogger().debug("POST at /directions")
		logger.getLogger().debug(request.json)
		print(request.json)

		# Check user validity
		if not "UserToken" in request.headers:
			return ResponseMaker.response_error(constants.PARAMERR, "Bad request - missing token")
		token = request.headers['UserToken']
		(valid, decoded) = TokenGenerator.validateToken(token)
		if not valid:
			return ResponseMaker.response_error(constants.FORBIDDEN, "Forbidden")

		# Check endpoints are in the request 
		if not request.json:
			return ResponseMaker.response_error(constants.PARAMERR, "Bad request - missing parameters")
		if not "origin" in request.json or not "destination" in request.json:
			return ResponseMaker.response_error(constants.PARAMERR, "Bad request")
		origin = request.json['origin']
		destination = request.json['destination']

		# Check for coordinates on endpoints
		if not "lat" in origin or not "lng" in origin:
			return ResponseMaker.response_error(constants.PARAMERR, "Bad request")
		if not "lat" in destination or not "lng" in destination:
			return ResponseMaker.response_error(constants.PARAMERR, "Bad request")

		origin_str = "origin=" + str(origin["lat"]) + "," + str(origin["lng"])
		print("origin_str = " + origin_str)
		destination_str = "destination=" + str(destination["lat"]) + "," + str(destination["lng"])
		
		r = requests.get(GOOGLE_DIRECTIONS + "?" + origin_str + "&" + destination_str + "&key=" + GOOGLE_API_KEY)

		r = r.json()
		print(r)

		if r["status"] != "OK":
			return ResponseMaker.response_error(500, "Google API error: " + r["status"])
		
		r = self.convert_response(r)

		trip = {}
		trip["directions"] = r
		trip["driverId"] = -1
		trip["passengerId"] = decoded["_id"]

		# (shared) Ask shared for a trip cost estimation
		try:
			(status_code, response) = ServerRequest.estimateTrip(TripStates.trip_to_shared(trip))
		except Exception as e:
			logger.getLogger().exception("No cost estimation from server: " + str(e))

		if not status_code == constants.SUCCESS:
			logger.getLogger().exception("No cost estimation from server: " + str(e))
			cost = {}
		else:
			cost = response["cost"]

		return ResponseMaker.response_object(200, ["directions", "cost"], [r, cost])
Exemple #9
0
    def put(self, id):
        print(id)
        print("PUT at /user/" + str(id) + "/rating")
        logger.getLogger().debug("PUT at /users/" + str(id) + "/rating")

        if not "UserToken" in request.headers:
            return ResponseMaker.response_error(constants.PARAMERR,
                                                "Bad request - missing token")

        token = request.headers['UserToken']
        (valid, decoded) = TokenGenerator.validateToken(token)

        if not valid or (decoded['_id'] != id):
            return ResponseMaker.response_error(constants.FORBIDDEN,
                                                "Forbidden")
        try:
            new_score = request.json["rate"]
            rating_count = [
                user["rating"]["rateCount"] for user in self.users.find()
                if user['_id'] == id and user['type'] == "driver"
            ][0]
            current_rate = [
                user["rating"]["rate"] for user in self.users.find()
                if user['_id'] == id and user['type'] == "driver"
            ][0]
            if len(rating_count) == 0 and len(current_rate) == 0:
                return ResponseMaker.response_error(constants.NOT_FOUND,
                                                    "User id not found.")
            #Recalculate rating
            rating_count += 1
            current_rate = current_rate + new_score
            #Update in local data-base
            self.users.update({'_id': id}, {
                "$set": {
                    "rating.rateCount": rating_count,
                    "rating.rate": current_rate
                }
            },
                              upsert=True)
            logger.getLogger().info("Successfully updated driver rating")

            driver = [
                user for user in self.users.find()
                if user['_id'] == id and user['type'] == "driver"
            ][0]
            return ResponseMaker.response_object(constants.SUCCESS, ['rating'],
                                                 [User.RatingUserJSON(driver)])
        except ValueError as e:
            logger.getLogger().error(str(e))
            return ResponseMaker.response_error(constants.UPDATE_CONFLICT,
                                                "User update failed:" + str(e))
        except requests.exceptions.Timeout as e:
            logger.getLogger().error(str(e))
            return ResponseMaker.response_error(constants.REQ_TIMEOUT,
                                                "User update failed:" + str(e))
        except Exception as e:
            logger.getLogger().error(str(e))
            return ResponseMaker.response_error(constants.ERROR, str(e))
Exemple #10
0
    def get(self):
        logger.getLogger().debug("GET at /trips")

        # (validate-token) Validate user token
        if not "UserToken" in request.headers:
            return ResponseMaker.response_error(constants.PARAMERR,
                                                "Bad request - missing token")

        token = request.headers['UserToken']
        (valid, requester) = TokenGenerator.validateToken(token)
        if not valid:
            return ResponseMaker.response_error(constants.UNAUTHORIZED,
                                                "Unauthorized")

        # Check if user is 1) logged in, and 2) a passenger
        (user, is_passenger) = self.userId_is_passenger(requester["_id"])

        if user == None:
            return ResponseMaker.response_error(
                constants.PARAMERR, "Bad request - user is not logged in")
        if is_passenger:
            return ResponseMaker.response_error(
                constants.FORBIDDEN, "Forbidden - user is not driver")

        logger.getLogger().debug("The 'driver' requesting trips is: " +
                                 str(user["_id"]) + "-" + user["username"])

        ## Actual getting of the trips!
        params = request.args

        active_trips = MongoController.getCollection("active_trips")
        trips = list(active_trips.find())

        if "filter" in params:
            trips = [
                trip for trip in trips if trip["state"] == params["filter"]
            ]

        if "sort" in params and params["sort"] == "near":
            trips.sort(key=lambda x: Distances.computeDistance(
                user["coord"], x["directions"]["origin"]))

        if "limit" in params:
            limit = int(params["limit"])
            if limit > 0:
                trips = trips[:(limit)]

        return ResponseMaker.response_object(constants.SUCCESS,
                                             ["message", "trips"],
                                             ["Getting trips!", trips])
Exemple #11
0
    def get(self, id):
        logger.getLogger().debug("GET at /users/" + str(id) + "/rating")
        if not "UserToken" in request.headers:
            return ResponseMaker.response_error(constants.PARAMERR,
                                                "Bad request - missing token")

        token = request.headers['UserToken']

        (valid, decoded) = TokenGenerator.validateToken(token)

        if not valid or (decoded['_id'] != id):
            return ResponseMaker.response_error(constants.FORBIDDEN,
                                                "Forbidden")

        try:
            print("GET at /users/" + str(id) + "/rating")
            candidates = [
                user for user in self.users.find() if user['_id'] == id
            ]

            if len(candidates) == 0:
                #If not available in local data-base, ask Shared-Server for user info.
                (status, response) = ServerRequest.getUser(id)
                if (status != constants.SUCCESS):
                    return ResponseMaker.response_error(
                        status, response["message"])
                candidates = [response]

            if len(candidates) == 0:
                logger.getLogger().error(
                    "Attempted to retrieve user with non-existent id.")
                return ResponseMaker.response_error(
                    constants.NOT_FOUND, "User id not found:" + str(e))

            if candidates[0]["type"] != "driver":
                return ResponseMaker.response_error(
                    constants.PARAMERR,
                    "The requested user is not a driver. Only drivers receive ratings."
                )
            return ResponseMaker.response_object(
                constants.SUCCESS, ['rating'],
                [User.RatingUserJSON(candidates[0])])

        except Exception as e:
            logger.getLogger().error(str(e))
            return ResponseMaker.response_error(constants.ERROR, str(e))
Exemple #12
0
    def put(self, id):
        print(id)
        print("PUT at /user/" + str(id) + "/loacation")
        logger.getLogger().debug("PUT at /users/" + str(id) + "/location")

        if not "UserToken" in request.headers:
            return ResponseMaker.response_error(constants.PARAMERR,
                                                "Bad request - missing token")

        token = request.headers['UserToken']
        (valid, decoded) = TokenGenerator.validateToken(token)

        if not valid or (decoded['_id'] != id):
            return ResponseMaker.response_error(constants.FORBIDDEN,
                                                "Forbidden")
        try:
            updated_location = request.json["coord"]
            #Update in local data-base
            self.users.update({'_id': id},
                              {"$set": {
                                  "coord": updated_location
                              }})
            logger.getLogger().info("Successfully updated user location")

            user = list(self.users.find({"_id": id}))[0]
            if not user["tripId"] == "" and user["type"] == "driver":
                ## Need to update the trip!
                TripStates.updateDriverLocation(user["tripId"], user)

            return ResponseMaker.response_object(constants.SUCCESS,
                                                 ['location'],
                                                 [updated_location])
        except ValueError as e:
            logger.getLogger().error(str(e))
            return ResponseMaker.response_error(constants.UPDATE_CONFLICT,
                                                "User update failed:" + str(e))
        except requests.exceptions.Timeout as e:
            logger.getLogger().error(str(e))
            return ResponseMaker.response_error(constants.REQ_TIMEOUT,
                                                "User update failed:" + str(e))
        except Exception as e:
            logger.getLogger().error(str(e))
            return ResponseMaker.response_error(constants.ERROR, str(e))
Exemple #13
0
    def get(self):
        logger.getLogger().debug("GET at /users")
        # (validate-token) Validate user token
        if not "UserToken" in request.headers:
            return ResponseMaker.response_error(constants.PARAMERR,
                                                "Bad request - missing token")

        token = request.headers['UserToken']

        (valid, response) = TokenGenerator.validateToken(token)

        if not valid:
            return ResponseMaker.response_error(constants.FORBIDDEN,
                                                "Forbidden")

        # (mongodb) Return all logged in users.
        users_online = MongoController.getCollection("online")
        aux = [User.UserJSON(user) for user in users_online.find()]
        user = list(users_online.find({"_id": response["_id"]}))
        if len(user) == 0:
            return ResponseMaker.response_error(
                constants.PARAMERR, "Bad request - you may not be loged in")

        user = user[0]

        ## Aditional params (only supporting "sort")
        params = request.args

        if "filter" in params:
            aux = [u for u in aux if u["type"] == params["filter"]]

        if "sort" in params and params["sort"] == "near":
            aux.sort(key=lambda x: Distances.computeDistance(
                user["coord"], x["coord"]))

        if "limit" in params:
            limit = int(params["limit"])
            if limit > 0:
                aux = aux[:(limit)]

        return ResponseMaker.response_object(constants.SUCCESS, ['users'],
                                             [aux])
Exemple #14
0
    def delete(self, userId, carId):
        print("DELETE at /users/id")
        logger.getLogger().debug("DELETE at /users/" + str(userId) + "/cars/" +
                                 str(carId))

        if not "UserToken" in request.headers:
            return ResponseMaker.response_error(constants.PARAMERR,
                                                "Bad request - missing token")

        token = request.headers['UserToken']

        (valid, decoded) = TokenGenerator.validateToken(token)

        print(decoded)
        if not valid or (decoded['_id'] != userId):
            return ResponseMaker.response_error(constants.FORBIDDEN,
                                                "Forbidden")
        try:
            #Ask Shared-Server to delete this user
            delete_success, status_code = ServerRequest.deleteUserCar(
                userId, carId)
            if delete_success:
                #Delete in local data-base
                self.users.update({"_id": id},
                                  {'$pull': {
                                      "cars": {
                                          "_id": carId
                                      }
                                  }})
                logger.getLogger().info("Successfully deleted user car.")
                return ResponseMaker.response_object(constants.DELETE_SUCCESS,
                                                     ['car'], {"id": carId})
            else:
                logger.getLogger().error(
                    "Attempted to delete car with non-existent id.")
                return ResponseMaker.response_error(status_code,
                                                    "Delete error")

        except Exception as e:
            print(str(e))
            return ResponseMaker.response_error(constants.ERROR,
                                                "Unexpected error")
Exemple #15
0
	def get(self, id):
		logger.getLogger().debug("GET at /users/" + str(id) + "/transactions")
		if not "UserToken" in request.headers:
			return ResponseMaker.response_error(constants.PARAMERR, "Bad request - missing token")

		token = request.headers['UserToken']

		(valid, decoded) = TokenGenerator.validateToken(token)

		print(decoded)
		if not valid or (decoded['_id'] != id):
			return ResponseMaker.response_error(constants.FORBIDDEN, "Forbidden")
		
		transactions = []#TODO:try fetch transactions from local database

		try:
			if (len(transactions) == 0):
				status_code, transactions = ServerRequest.getUserTransactions(id)
		except Exception as e:
			return ResponseMaker.response_error(constants.NOT_FOUND, "User id did not match any existing users." + str(e))			
		return ResponseMaker.response_object(constants.SUCCESS, ['transactions'], [transactions])
Exemple #16
0
	def get(self):
		logger.getLogger().debug("GET at /payment")
		# (validate-token) Validate user token
		if not "UserToken" in request.headers:
			return ResponseMaker.response_error(constants.PARAMERR, "Bad request - missing token")

		token = request.headers['UserToken']

		(valid, response) = TokenGenerator.validateToken(token)

		if not valid:
			return ResponseMaker.response_error(constants.FORBIDDEN, "Forbidden")
		
		status_code, response = ServerRequest.getPaymethods()
		
		if (status_code != constants.SUCCESS):
			return ResponseMaker.response_object(constants.ERROR, response['message'])
			
		print(response)
		
		return ResponseMaker.response_object(constants.SUCCESS, ['paymethods'], [response['paymethods']])
Exemple #17
0
    def put(self, id):
        print(id)
        print("PUT at /user/id")
        logger.getLogger().debug("PUT at /users/" + str(id))

        if not "UserToken" in request.headers:
            return ResponseMaker.response_error(constants.PARAMERR,
                                                "Bad request - missing token")

        token = request.headers['UserToken']
        (valid, decoded) = TokenGenerator.validateToken(token)

        if not valid or (decoded['_id'] != id):
            return ResponseMaker.response_error(constants.FORBIDDEN,
                                                "Forbidden")
        try:
            #Ask Shared-Server to update this user
            success, updated_user = ServerRequest.updateUser(request.json)
            if success:
                #Update in local data-base
                self.users.update({'_id': updated_user['id']},
                                  User.UserJSON(updated_user),
                                  upsert=True)
                logger.getLogger().info("Successfully updated user")
                return ResponseMaker.response_error(
                    constants.SUCCESS, "User updated successfully!")
            return ResponseMaker.response_error(constants.NOT_FOUND,
                                                "User not found!")
        except ValueError as e:
            logger.getLogger().error(str(e))
            return ResponseMaker.response_error(constants.UPDATE_CONFLICT,
                                                "User update failed:" + str(e))
        except requests.exceptions.Timeout as e:
            logger.getLogger().error(str(e))
            return ResponseMaker.response_error(constants.REQ_TIMEOUT,
                                                "User update failed:" + str(e))
        except Exception as e:
            logger.getLogger().error(str(e))
            return ResponseMaker.response_error(constants.FORBIDDEN,
                                                "Forbidden: " + str(e))
Exemple #18
0
    def post(self, id):
        print(request.json)
        logger.getLogger().debug("POST at /users/cars")
        logger.getLogger().debug(request.json)

        try:

            if not "UserToken" in request.headers:
                return ResponseMaker.response_error(
                    constants.PARAMERR, "Bad request - missing token")

            token = request.headers['UserToken']

            (valid, decoded) = TokenGenerator.validateToken(token)

            print(decoded)
            if not valid or (decoded['_id'] != id):
                return ResponseMaker.response_error(constants.FORBIDDEN,
                                                    "Forbidden")

            #Create car at shared server.
            (status, response) = ServerRequest.createUserCar(id, request.json)

            if (status != constants.CREATE_SUCCESS):
                return ResponseMaker.response_error(status,
                                                    response["message"])

            #Update local database
            car = response
            car["_id"] = car.pop("id")
            self.users.update({"_id": id}, {"$push": {"cars": car}})
            return ResponseMaker.response_object(status, ["car"], [car])

        except Exception as e:
            logger.getLogger().debug(str(e))
            print(str(e))
            return ResponseMaker.response_error(constants.ERROR,
                                                "Unexpected error: " + str(e))
Exemple #19
0
    def get(self, id):
        logger.getLogger().debug("GET at /users/" + str(id) + "/trips")
        if not "UserToken" in request.headers:
            return ResponseMaker.response_error(constants.PARAMERR,
                                                "Bad request - missing token")

        token = request.headers['UserToken']

        (valid, decoded) = TokenGenerator.validateToken(token)

        if not valid or (decoded['_id'] != id):
            return ResponseMaker.response_error(constants.UNAUTHORIZED,
                                                "Unauthorized")

        print("GET at /user/id/trips")
        #Search local database
        trips = []  #[user for user in self.users.find() if user['_id'] == id]

        if len(trips) == 0:
            #If not available in local data-base, ask Shared-Server for user info.
            (status, response) = ServerRequest.getUserTrips(id)

            if (status != constants.SUCCESS):
                return ResponseMaker.response_error(status,
                                                    response["message"])

        #TODO: fetch user from ss and store locally
        trips = response

        if (status == constants.NOT_FOUND):
            logger.getLogger().error(
                "Attempted to retrieve non-existent user trip list.")
            return ResponseMaker.response_error(constants.NOT_FOUND,
                                                "Trip list not found.")

        return ResponseMaker.response_object(constants.SUCCESS, ['trips'],
                                             [trips])
Exemple #20
0
    def post(self):
        print(request.json)
        logger.getLogger().debug("POST at /trips")
        logger.getLogger().debug(request.json)

        # (validate-token) Validate user token
        if not "UserToken" in request.headers:
            return ResponseMaker.response_error(constants.PARAMERR,
                                                "Bad request - missing token")

        token = request.headers['UserToken']
        (valid, requester) = TokenGenerator.validateToken(token)
        if not valid:
            return ResponseMaker.response_error(constants.UNAUTHORIZED,
                                                "Unauthorized")

        # Check if user is 1) logged in, and 2) a passenger
        (user, is_passenger) = self.userId_is_passenger(requester["_id"])

        if user == None:
            return ResponseMaker.response_error(
                constants.PARAMERR, "Bad request - user is not logged in")
        if not is_passenger:
            return ResponseMaker.response_error(
                constants.FORBIDDEN, "Forbidden - user is not passenger")

        logger.getLogger().debug("The 'passenger' requesting the trip is: " +
                                 str(user["_id"]) + "-" + user["username"])

        if not user["state"] == User.USER_PSG_IDLE:
            return ResponseMaker.response_error(
                constants.PARAMERR, "Bad request - user is not in idle state!")

        # Check the trip data is valid!
        trip = request.json
        if trip == None:
            return ResponseMaker.response_errPSG_or(
                constants.PARAMERR, "Bad request - missing trip data")
        if not self.check_new_trip(trip):
            return ResponseMaker.response_error(constants.PARAMERR,
                                                "Bad request - bad trip data")

        # Creating a new trip
        new_trip = {}
        new_trip["directions"] = trip
        new_trip["passengerId"] = requester["_id"]
        new_trip["driverId"] = -1
        new_trip["state"] = TripStates.TRIP_PROPOSED
        new_trip["_id"] = str(uuid.uuid1())
        logger.getLogger().debug("Created trip with uudi: " + new_trip["_id"])

        # (shared) Ask shared for a trip cost estimation
        (status, response) = ServerRequest.estimateTrip(
            TripStates.trip_to_shared(new_trip))
        try:
            (status, response) = ServerRequest.estimateTrip(
                TripStates.trip_to_shared(new_trip))
        except Exception as e:
            logger.getLogger().exception("No cost estimation from server: " +
                                         str(e))
            return ResponseMaker.response_error(
                constants.ERROR,
                "Internal server error - there is no estimation")

        if not status == constants.SUCCESS:
            logger.getLogger().exception("No cost estimation from server: " +
                                         str(e))
        else:
            new_trip["cost"] = response["cost"]

        # (mongodb) Storing new trip in the db!
        active_trips = MongoController.getCollection("active_trips")
        active_trips.insert_one(new_trip)

        users = MongoController.getCollection("online")
        users.update_one({"_id": user["_id"]}, {
            "$set": {
                "state": User.USER_PSG_WAITING_ACCEPT,
                "tripId": new_trip["_id"]
            }
        })

        return ResponseMaker.response_object(constants.SUCCESS,
                                             ["message", "trip"],
                                             ["Trip created!", new_trip])
Exemple #21
0
 def test_invalid_decode(self):
     token = "This is a fake token"
     valid, decoded = TokenGenerator.validateToken(token)
     assert ('Invalid token' in decoded)
     assert (valid == False)
Exemple #22
0
	def post(self, id):
		logger.getLogger().debug("GET at /trips/" + str(id))

		# (validate-token) Validate user token
		if not "UserToken" in request.headers:
			return ResponseMaker.response_error(constants.PARAMERR, "Bad request - missing token")

		token = request.headers['UserToken']
		(valid, user) = TokenGenerator.validateToken(token)

		if not valid:
			return ResponseMaker.response_error(constants.UNAUTHORIZED, "Unauthorized")
		
		active_trips = MongoController.getCollection("active_trips")
		trip = list(active_trips.find({"_id" : id}))

		if len(trip) == 0:
			return ResponseMaker.response_error(constants.NOT_FOUND, "Not found")

		# This should never happen
		if len(trip) > 1:
			return ResponseMaker.response_error(constants.ERROR, "Internal server error - more than one trip with same ID")

		trip = trip[0]
		#print(trip)

		action = request.json
		users = MongoController.getCollection("online")
		if action == None:
			return ResponseMaker.response_error(constants.PARAMERR, "Bad request - missing action")

		if not "action" in action:
			return ResponseMaker.response_error(constants.PARAMERR, "Bad request - missing action")

		if action["action"] == TripStates.ACTION_CANCEL:
			print("Someone wants to delete trip " + trip["_id"])
			return self.cancel_handler(action, trip, user["_id"])

		if action["action"] == TripStates.ACTION_DRIVER_ACCEPT:
			print("Someone wants to accept the trip " + trip["_id"])
			return self.accept_handler(action, trip, user["_id"])

		if action["action"] == TripStates.ACTION_PASSENGER_CONFIRM:
			print("Passenger wants to confirm the driver " + trip["_id"])
			return self.confirm_handler(action, trip, user["_id"])

		if action["action"] == TripStates.ACTION_PASSENGER_REJECT:
			print("Passenger wants to reject the driver " + trip["_id"])
			return self.reject_handler(action, trip, user["_id"])

		if action["action"] == TripStates.ACTION_START:
			print("Someone wants to start the trip " + trip["_id"])
			return self.start_handler(action, trip, user["_id"])

		if action["action"] == TripStates.ACTION_FINISH:
			print("Someone wants to finish the trip" + trip["_id"])
			return self.finish_handler(action, trip, user["_id"])

		if action["action"] == TripStates.ACTION_RATE:
			print("Passenger wants to rate the driver " + trip["_id"])
			if not "rating" in action:
				return ResponseMaker.response_error(constants.PARAMERR, "Bad request - rating action without rating")
			return self.rate_handler(action, trip, user["_id"])

		if action["action"] == TripStates.ACTION_PAY:
			print("Passenger wants to pay " + trip["_id"])
			if not "paymethod" in action:
				return ResponseMaker.response_error(constants.PARAMERR, "Bad request - missing payment info")
			return self.payment_handler(action, trip, user["_id"])

		return ResponseMaker.response_object(constants.SUCCESS, ["message", "action"], ["No action performed. Invalid action.", action["action"]])
Exemple #23
0
 def test_decoded_gives_same_payload(self):
     payload = {"username": "******", "_id": 1}
     token = TokenGenerator.generateToken(payload)
     valid, decoded = TokenGenerator.validateToken(token)
     assert (valid == True)
     assert (decoded == payload)