Пример #1
0
 def user_is_present(email: str = None, phone: str = None):
     """
     This method contains the logic to search a user with the
     :param email: user email if it is present we use to filter user
     :param phone: phone number, if it is present we use to filter user
     :return: use user if exist otherwise, it is return None
     """
     try:
         url = USER_MICROSERVICE_URL
         json = {}
         if email is not None and len(email) != 0:
             url = "{}/user_by_email".format(url)
             json["email"] = email
         else:
             url = "{}/user_by_phone".format(url)
             json["phone"] = phone
         current_app.logger.debug("Url is {}".format(url))
         response = requests.post(url=url, json=json)
     except requests.exceptions.ConnectionError as ex:
         current_app.logger.error(
             "Error during the microservice call {}".format(str(ex)))
         return None
     current_app.logger.debug("Response is {}".format(response.text))
     json = response.json()
     if response.ok is False:
         current_app.logger.error("Request error: {}".format(json))
         return None
     current_app.logger.debug("User found is: {}".format(json))
     user = UserModel()
     user.fill_from_json(json)
     return user
Пример #2
0
    def post(self):
        """Registers a new user via POST HTTP request
        
        Returns:
            JSON object: A 200 HTTP status response with name of the user

            JSON object: A 404 HTTP status response for an existing user

        Raises:
            Exception: General exceptions aligned to SQLAlchemy in the form of a 500 HTTP status and 
                JSON content-type response

        """
        data_user_details = self.get_user_details_parsed_args()
        data_password = self.get_user_password_parsed_args()

        try:
            # check if user exists by using email address value
            if not self.check_existing_user(data_user_details['email']):
                user = UserModel(
                    email=data_user_details['email'],
                    name=data_user_details['name'],
                    password=UserModel.generate_hash(
                        data_password['password']))
                user.save_to_db()
                return {
                    "message":
                    "User {} was created".format(data_user_details['name'])
                }, 200
            else:
                return {"message": "That email address already exists"}, 400
        except Exception as e:
            return {"message": str(e)}, 500
Пример #3
0
 def get_user_by_id(user_id):
     """"""
     user = "******".format(USER_MICROSERVICE_URL, user_id)
     response = HttpUtils.make_get_request(user)
     if response is None:
         return None
     user_model = UserModel()
     user_model.fill_from_json(response)
     return user_model
Пример #4
0
 def get_list_of_positive_user():
     """
     This method perform the request to get all positive user inside the database
     """
     url = "{}/report_positive".format(USER_MICROSERVICE_URL)
     response = HttpUtils.make_get_request(url)
     if response is None or len(response) == 0:
         return []
     users = response["users"]
     list_user = []
     for user in users:
         new_user = UserModel()
         new_user.fill_from_json(user)
         list_user.append(new_user)
     return list_user
Пример #5
0
    def modify_user(user_form: UserForm,
                    role_id: int = None,
                    user_id: int = None):
        """
        This method take an user that is populate from te called (e.g: the flat form)
        and make the operation to store it as persistent (e.g database).
        We can assume that by default is not possible change the password
        :param form: the user form with new data
        :param user_id: it is used only for test because the session is not available
        :param role_id: by default is none but it is possible setup to change also the role id
        :return: the user with the change if is changed
        """
        if user_id is None:
            user_id = current_user.id
        if role_id is None:
            role_id = current_user.role_id

        email = user_form.email.data
        current_app.logger.debug("New user email {}".format(email))
        phone = user_form.phone.data
        current_app.logger.debug("New user phone {}".format(phone))
        date = user_form.dateofbirth.data
        current_app.logger.debug("New user birth {}".format(date))
        firstname = user_form.firstname.data
        current_app.logger.debug("New user firstname {}".format(firstname))
        lastname = user_form.lastname.data
        current_app.logger.debug("New user lastname {}".format(lastname))
        json_request = {
            "email": email,
            "phone": phone,
            "dateofbirth": str(date),
            "firstname": firstname,
            "lastname": lastname,
            "role": role_id,
            "id": user_id,
        }
        current_app.logger.debug("Request body \n{}".format(json_request))
        url = "{}/data/".format(USER_MICROSERVICE_URL)
        response = HttpUtils.make_put_request(to_url=url, args=json_request)
        if response[0] is None:
            current_app.logger.debug("An error with code occurs {}".format(
                response[1]))
            return None
        json = response[0]
        current_app.logger.debug("Response: ".format(json))
        user = UserModel()
        user.fill_from_json(json)
        return user
Пример #6
0
 def login_user(email: str, password: str) -> (UserModel, int):
     """
     This method perform the http request to perform the login on user microservices
     :return It return the user if the login has success
     """
     current_app.logger.debug("Email user: {}".format(email))
     current_app.logger.debug("Password is {}".format(password))
     url = "{}/login".format(USER_MICROSERVICE_URL)
     current_app.logger.debug("URL to call microservices: {}".format(url))
     json = {"email": email, "password": password}
     response, status_code = HttpUtils.make_post_request(url, json)
     if response is None:
         return None, status_code
     user = UserModel()
     user.fill_from_json(response)
     return user, status_code
Пример #7
0
 def setUp(self):
     self.app = create_app("testing")
     self.client = self.app.test_client
     self.user1 = {
         'name': 'user',
         'email': '*****@*****.**',
         'password': '******'
     }
     self.rental1 = {'movie_id': 1, 'user_id': 1}
     with self.app.app_context():
         # create all tables
         db.create_all()
         movie = MovieModel(movie_schema.load({'title': 'test'}))
         movie.save()
         user = UserModel(user_schema.load(self.user1))
         user.save()
Пример #8
0
 def get_user_by_email(email):
     try:
         url = "{}/email".format(USER_MICROSERVICE_URL, email)
         current_app.logger.debug("Url is: {}".format(url))
         response = requests.post(url, json={"email": email})
     except requests.exceptions.ConnectionError as ex:
         current_app.logger.error(
             "Error during the microservice call {}".format(str(ex)))
         return None
     if not response.ok:
         current_app.logger.error("Microservice response is: {}".format(
             response.text))
         return None
     user = UserModel()
     current_app.logger.debug("Microservice response is: {}".format(
         response.json()))
     user.fill_from_json(response.json())
     return user
Пример #9
0
def load_user(user_id):
    # user = User.query.get(user_id)
    if "current_user" in session:
        user = UserModel()
        user.fill_from_json(session["current_user"])
        user.set_authenticated(True)
        return user
    return None
Пример #10
0
    def log_in_user(user: UserModel):
        session["current_user"] = user.serialize()
        login_user(user)
        try:
            url = "{}/role/{}".format(USER_MICROSERVICE_URL, str(user.role_id))
            current_app.logger.debug("Url is {}".format(url))
            response = requests.get(url=url)
        except requests.exceptions.ConnectionError as ex:
            current_app.logger.error(
                "Error during the microservice call {}".format(str(ex)))
            return False
        json_response = response.json()
        current_app.logger.debug(
            "Response json content is: {}".format(json_response))
        if not response.ok:
            current_app.logger.error(json_response)
            return False

        role_value = json_response["value"]

        # set the role in the session
        session["ROLE"] = role_value

        if role_value == "OPERATOR":
            # TODO
            # get from restaurant microservice the restaurant of the user
            # and set the session
            try:
                url = "{}/id/{}".format(RESTAURANTS_MICROSERVICE_URL,
                                        str(user.email))
                current_app.logger.debug(
                    "Getting the restaurant of the user: Url is {}".format(
                        url))
                response = requests.get(url=url)
            except requests.exceptions.ConnectionError as ex:
                current_app.logger.error(
                    "Error during the microservice call {}".format(str(ex)))
                return False

            if response.ok:
                restaurant = RestaurantModel()
                current_app.logger.debug(
                    "Creating Restaurant model starting from: {}".format(
                        response.json()))
                restaurant.fill_from_json(response.json())

                session["RESTAURANT_ID"] = restaurant.id
                session["RESTAURANT_NAME"] = restaurant.name

        return True
Пример #11
0
    def post(self):
        """Receives data from HTTP POST request

        Returns:
            JSON object: 200 HTTP response with a dictionary of a user's details

            JSON object: 403 HTTP response with a dictionary of an error message
            
            JSON object: 404 HTTP response with a dictionary of an error message
            
            JSON object: 500 HTTP response with a dictionary of an error message

        """
        data = self.get_login_details()

        try:
            user = UserModel.query.filter_by(email=data['email']).first()

            # return 404 response if user's email does not exist
            if not user:
                return {"message": "This user does not exist"}, 404
            else:
                # get authentication token
                auth_token = encode_jwt(subject_id=user.id,
                                        secret=get_secret_key())

                # verify password and return 403 response if it's wrong
                if UserModel.verify_hash(data['password'], user.password):
                    response = {
                        "user_id": user.id,
                        "message": "Logged in as {}".format(user.name),
                        "auth_token":
                        auth_token.decode()  # decode from bytes to string
                    }
                    return response, 200
                else:
                    return {"message": "wrong user credentials"}, 401
        except Exception as e:
            return {"message": str(e)}, 500
Пример #12
0
    def put(self):
        """Updates details of a user via PUT HTTP request
        
        Returns:
            JSON object: A 200 HTTP status response with name of the user that was updated

            JSON object: A 404 HTTP status response for a user that does not exist

        Raises:
            Exception: General exceptions aligned to SQLAlchemy in the form of a 500 HTTP status and 
                JSON content-type response

        """
        data_user_id = self.get_user_id_parsed_args()
        data_user_details = self.get_user_details_parsed_args()
        data_password = self.get_user_password_parsed_args()

        try:
            user = UserModel.query.filter_by(
                id=data_user_id['user_id']).first()

            if user:
                user.email = data_user_details['email']
                user.name = data_user_details['name']
                user.password = UserModel.generate_hash(
                    data_password['password'])
                user.updated_at = datetime.utcnow()
                user.save_to_db()
                return {
                    "message":
                    "User {} was updated".format(data_user_details['name'])
                }, 200
            else:
                return {"message": "This user does not exist"}, 404
        except Exception as e:
            return {"message": str(e)}, 500