Пример #1
0
    def post(cls):
        """Post method"""
        user_data = user_schema.load(request.get_json())

        if UserModel.find_by_username(user_data.username):
            return {
                "message": "A user with that username already exists."
            }, 400

        user_data.password = generate_password_hash(user_data.password)
        user_data.is_admin = False
        user_data.is_staff = False

        try:
            user_data.save_to_db()
            user = UserModel.find_by_username(user_data.username)
            user_profile = UserProfileModel(user_id=user.id)
            user_profile.save_to_db()
            expires = datetime.timedelta(days=1)
            access_token = create_access_token(identity=user.id,
                                               fresh=True,
                                               expires_delta=expires)

        except:
            return {"message": "An error occurred creating the user."}, 500

        return (
            {
                "message": "User created successfully.",
                "access_token": access_token,
                "username": user.username,
                "user": user.id,
            },
            201,
        )
Пример #2
0
    def post(cls):
        """Register a user"""
        claims = get_jwt_claims()
        if not claims["is_admin"]:
            return (
                {
                    "message": "You don't have permission to perform this action."
                },
                403,
            )

        user_data = user_schema.load(request.get_json())
        if UserModel.find_by_username(user_data.username):
            return {"message": "A user with that username already exists."}, 400

        user_data.password = generate_password_hash(user_data.password)

        try:
            user_data.save_to_db()
            user = UserModel.find_by_username(user_data.username)
            user_profile = UserProfileModel(user_id=user.id)
            user_profile.save_to_db()

        except:
            return {"message": "An error occurred creating the user."}, 500
        return {"message": "User created successfully."}, 201
    def test_userprofile_is_deleted_from_db(self):
        """Test if the user profile has been successfully deleted
         from the database"""
        user = self._create_sample_user("test")
        userprofile = UserProfileModel.find_by_user_id(user.id)
        userprofile.delete_from_db()
        found_userprofile = UserProfileModel.find_by_user_id(user.id)

        self.assertIsNone(found_userprofile)
    def test_userprofile_is_saved_in_db(self):
        """Test if the user profile has been successfully saved in the database
        after creating a new user"""
        user = UserModel(username="******", password="******")
        user.save_to_db()
        userprofile = UserProfileModel(user_id=user.id)
        userprofile.save_to_db()
        found_userprofile = UserProfileModel.find_by_username(user.username)

        self.assertIsNotNone(found_userprofile)
 def create_admin(self):
     """Create a user model and a user profile model
     and save them to the database"""
     with app.app_context():
         hashed_pass = generate_password_hash(self.password)
         user = UserModel(
             username=self.username,
             password=hashed_pass,
             is_admin=True,
             is_staff=True,
         )
         user.save_to_db()
         user_profile = UserProfileModel(user_id=user.id)
         user_profile.save_to_db()
Пример #6
0
    def delete(cls, training_id: int):
        """Delete method"""
        current_user_id = get_jwt_identity()
        user_profile = UserProfileModel.find_by_user_id(current_user_id)
        training = TrainingModel.find_by_id(training_id)
        if not training:
            return {"message": "Training not found."}, 404
        if training.user_id != current_user_id:
            return (
                {
                    "message":
                    "You don't have permission to perform this action."
                },
                403,
            )

        user_profile.trainings_number -= 1
        user_profile.kilometers_run -= training.distance
        try:
            training.delete_from_db()
            user_profile.save_to_db()
        except:
            return (
                {
                    "message": "An error has occurred deleting the training."
                },
                500,
            )
        return {"message": "Training deleted"}, 200
    def test_find_all(self):
        """Test if all the user profiles which exist in the database
         are returned"""
        self._create_sample_user("test1")
        self._create_sample_user("user2")
        found_userprofiles = UserProfileModel.find_all()

        self.assertEqual(len(found_userprofiles), 2)
 def setUp(self):
     """Set up a test app, test client and test database"""
     self.app = self._set_up_test_app(create_app)
     self.client = self._set_up_client(self.app)
     self._set_up_test_db(db)
     self.user = self._create_sample_user(
         age=25, gender="Female", height=165, weight=58
     )
     self.user_profile = UserProfileModel.find_by_user_id(self.user.id)
Пример #9
0
 def _create_sample_user(
     cls,
     username: str = "testuser",
     height=185,
     weight=70,
     gender="Male",
     age=25,
 ) -> "UserModel":
     """Create a sample user"""
     user = UserModel(username=username,
                      password=generate_password_hash("testpass"))
     user.save_to_db()
     user_profile = UserProfileModel(
         user_id=user.id,
         height=height,
         weight=weight,
         gender=gender,
         age=age,
     )
     user_profile.save_to_db()
     return user
Пример #10
0
    def put(cls, training_id: int):
        """Put method"""
        current_user_id = get_jwt_identity()
        user_profile = UserProfileModel.find_by_user_id(current_user_id)
        training = TrainingModel.find_by_id(training_id)
        if not training:
            return {"message": "Training not found."}, 404
        if training.user_id != current_user_id:
            return (
                {
                    "message":
                    "You don't have permission to perform this action."
                },
                403,
            )

        user_profile.kilometers_run -= training.distance
        training_data = training_schema.load(request.get_json())
        if (TrainingModel.find_by_name_and_user_id(
                training_data.name, current_user_id) != training):
            return (
                {
                    "message":
                    f"You have already created a training "
                    f"called {training_data.name}. "
                    f"Choose another name."
                },
                400,
            )  # bad request

        training.name = training_data.name
        training.distance = training_data.distance
        user_profile.kilometers_run += training.distance
        training.time_in_seconds = training_data.time_in_seconds
        training.calculate_average_tempo()
        training.calculate_calories_burnt()

        try:
            training.save_to_db()
            user_profile.save_to_db()
        except:
            return (
                {
                    "message": "An error has occurred updating the training."
                },
                500,
            )
        return training_schema.dump(training), 200
Пример #11
0
 def delete(cls, user_id: int):
     """Delete method"""
     current_user_id = get_jwt_identity()
     user = UserModel.find_by_id(user_id)
     if not user:
         return {"message": "User not found."}, 404
     if current_user_id != user_id:
         return (
             {
                 "message":
                 "You don't have permission to perform this action."
             },
             403,
         )
     user_profile = UserProfileModel.find_by_user_id(user_id)
     user_profile.delete_from_db()
     user.delete_from_db()
     return {"message": "User deleted."}, 200
Пример #12
0
    def delete(cls, user_id):
        """Delete the user"""
        claims = get_jwt_claims()
        if not claims["is_admin"]:
            return (
                {
                    "message": "You don't have permission to perform this action."
                },
                403,
            )

        user = UserModel.find_by_id(user_id)
        if not user:
            return {"message": "User not found."}, 404
        user_profile = UserProfileModel.find_by_user_id(user_id)
        user_profile.delete_from_db()
        user.delete_from_db()
        return {"message": "User deleted."}, 200
Пример #13
0
    def post(cls):
        """Post method"""
        current_user_id = get_jwt_identity()
        user_profile = UserProfileModel.find_by_user_id(current_user_id)
        json_data = daily_needs_schema.load(request.get_json())

        user_profile.daily_cal = json_data["daily_cal"]
        try:
            user_profile.save_to_db()
        except:
            return {"message": "An error has occurred updating the user."}, 500

        return (
            {
                "message": "Daily caloric needs have been updated",
                "daily_cal": json_data["daily_cal"],
            },
            201,
        )
Пример #14
0
    def post(cls):
        """Post method"""
        training_json = request.get_json()
        current_user_id = get_jwt_identity()
        user_profile = UserProfileModel.find_by_user_id(current_user_id)
        training = TrainingModel.find_by_name_and_user_id(
            training_json["name"], current_user_id)
        if training:
            return (
                {
                    "message":
                    f"You have already created a training "
                    f"called {training_json['name']}. "
                    f"Choose another name."
                },
                400,
            )  # bad request

        training = training_schema.load(training_json)
        training.user_id = current_user_id
        training.calculate_average_tempo()
        training.calculate_calories_burnt()
        user_profile.trainings_number += 1
        user_profile.kilometers_run += training.distance

        try:
            training.save_to_db()
            user_profile.save_to_db()
        except:
            return (
                {
                    "message": "An error has occurred inserting the training."
                },
                500,
            )  # internal server error
        return training_schema.dump(training), 201
Пример #15
0
    def put(cls, userprofile_id: int):
        """Put method"""
        user_profile = UserProfileModel.find_by_id(userprofile_id)
        if not user_profile:
            return {"message": f"User profile not found."}, 404

        current_user_id = get_jwt_identity()

        if userprofile_id != current_user_id:
            return (
                {
                    "message":
                    "You don't have permission to perform this action."
                },
                403,
            )

        user_profile_data = user_profile_schema.load(request.get_json())
        user_profile.gender = user_profile_data.gender
        user_profile.age = user_profile_data.age
        user_profile.height = user_profile_data.height
        user_profile.weight = user_profile_data.weight
        user_profile.calculate_bmi()

        try:
            user_profile.save_to_db()
        except:
            return (
                {
                    "message":
                    "An error has occurred updating the user profile."
                },
                500,
            )

        return user_profile_schema.dump(user_profile), 200
Пример #16
0
 def __given_test_user_is_created(self):
     self.user1 = self._create_sample_user(username="******")
     self.user_profile1 = UserProfileModel.find_by_user_id(self.user1.id)
     self.access_token = self._get_access_token(self.client)
Пример #17
0
 def __given_other_user_is_created(self):
     self.user2 = self._create_sample_user(username="******")
     self.user_profile2 = UserProfileModel.find_by_user_id(self.user2.id)
Пример #18
0
    def __given_user_profile_is_none(self, user_profile_id):
        user_profile = UserProfileModel.find_by_id(user_profile_id)

        self.assertIsNone(user_profile)
Пример #19
0
 def _get_users_weight(self) -> int:
     """Access user's weight by user profile"""
     user_profile = UserProfileModel.find_by_user_id(self.user_id)
     return user_profile.weight
    def test_find_by_username(self):
        """Test if the user profile is found"""
        user = self._create_sample_user("test")
        found_userprofile = UserProfileModel.find_by_username("test")

        self.assertEqual(found_userprofile.user_id, user.id)
    def test_find_all_no_users(self):
        """Test if an empty list is returned
        if there are no trainings in the database"""
        found_userprofiles = UserProfileModel.find_all()

        self.assertEqual(found_userprofiles, [])
    def test_find_by_username_no_user(self):
        """Test if None is returned
        if the user with the given username doesn't exist"""
        found_userprofile = UserProfileModel.find_by_username("test")

        self.assertIsNone(found_userprofile)
    def test_find_by_id_no_user(self):
        """Test if None is returned
        if the user profile with the given id doesn't exist"""
        found_userprofile = UserProfileModel.find_by_id(1)

        self.assertIsNone(found_userprofile)
    def test_find_by_id(self):
        """Test if the user profile is found"""
        self._create_sample_user("test")
        found_userprofile = UserProfileModel.find_by_id(1)

        self.assertIsNotNone(found_userprofile)