def setUp(self):
        super(TestnGetOtherUserApi, self).setUp()

        self.verified_user = UserModel(
            name=user1["name"] + "    Example",
            email=user1["email"],
            username=user1["username"],
            password=user1["password"],
            terms_and_conditions_checked=user1["terms_and_conditions_checked"],
        )
        self.other_user = UserModel(
            name=user2["name"],
            email=user2["email"],
            username=user2["username"],
            password=user2["password"],
            terms_and_conditions_checked=user2["terms_and_conditions_checked"],
        )

        self.verified_user.is_email_verified = True
        self.verified_user.is_available = False
        self.other_user.is_email_verified = True
        self.other_user.is_available = False
        db.session.add(self.verified_user)
        db.session.add(self.other_user)
        db.session.commit()
Beispiel #2
0
    def test_dao_confirm_registration_of_already_verified_user(self):
        dao = UserDAO()

        user = UserModel(
            name=user2["name"],
            email=user2["email"],
            username=user2["username"],
            password=user2["password"],
            terms_and_conditions_checked=user2["terms_and_conditions_checked"],
        )
        db.session.add(user)
        db.session.commit()

        # Verify that user was inserted in database through DAO
        user = UserModel.query.filter_by(email=user2["email"]).first()
        self.assertIsNotNone(user)
        user.is_email_verified = True
        db.session.add(user)
        db.session.commit()

        self.assertTrue(user.is_email_verified)
        good_token = generate_confirmation_token(user2["email"])
        actual_result = dao.confirm_registration(good_token)

        self.assertTrue(user.is_email_verified)
        self.assertEqual((messages.ACCOUNT_ALREADY_CONFIRMED, 200),
                         actual_result)
    def delete_user(user_id: int):
        """ Deletes a user.

        Deletes the specified user and removes them from the directory, with checks to make sure that the user exists and is not the only administrator.

        Arguments:
            user_id: The ID of the user to be deleted.

        Returns:
            A tuple with two elements. The first element is a dictionary containing a key 'message' containing a string which indicates whether or not the user was created successfully. The second is the HTTP response code.
        """

        user = UserModel.find_by_id(user_id)

        # check if this user is the only admin
        if user.is_admin:

            admins_list_count = len(UserModel.get_all_admins())
            if admins_list_count <= UserDAO.MIN_NUMBER_OF_ADMINS:
                return messages.USER_CANT_DELETE, HTTPStatus.BAD_REQUEST

        if user:
            user.delete_from_db()
            return messages.USER_SUCCESSFULLY_DELETED, HTTPStatus.OK

        return messages.USER_DOES_NOT_EXIST, HTTPStatus.NOT_FOUND
    def setUp(self):
        super().setUp()

        self.mentor = UserModel(
            name="Mentor A",
            email=user1["email"],
            username=user1["username"],
            password=user1["password"],
            terms_and_conditions_checked=user1["terms_and_conditions_checked"],
        )  # User A

        self.mentee = UserModel(
            name="Mentee B",
            email=user2["email"],
            username=user2["username"],
            password=user2["password"],
            terms_and_conditions_checked=user2["terms_and_conditions_checked"],
        )  # User B

        self.mentor.is_email_verified = True
        self.mentee.is_email_verified = True

        self.mentor.available_to_mentor = True
        self.mentee.need_mentoring = True

        db.session.add(self.mentor)
        db.session.add(self.mentee)
        db.session.commit()

        self.test_description = "A nice task description"
Beispiel #5
0
 def send_invite_to_mod(firebase_id: str, email: str):
     mod_email = email
     
     try:
         user = UserModel.find_by_firebase_id(firebase_id)
     except Exception as e:
         return messages.CANNOT_FIND_USER, 400
     
     if user.is_donor:
         mod_exists = UserModel.find_by_email(mod_email)
         if mod_exists:
             if mod_exists.is_moderator:
                 return {"message": f"Moderator is already registered. Do you want to proceed?"}, 409
             else:
                 role = "donor" if mod_exists.is_donor else "recipient" if mod_exists.is_recipient else "moderator"
                 return {"message": f"User with this email is already signed up as a {role}"}, 400
         else:
             otp = random.randint(111111,999999)
             invite = InvitesModel(user, email, otp)
             invite.save_to_db()
             send_invite_mod_email(user.name, otp, email)
             return {"message": "Invitation sent"}, 200
             
     else:
         return {"message": "User cannot invite moderator"}, 401
    def setUp(self):
        super(TestHomeStatisticsApi, self).setUp()

        self.user1 = UserModel("User1", "user1", "__test__", "*****@*****.**", True)
        self.user2 = UserModel("User2", "user2", "__test__", "*****@*****.**", True)
        self.user1.available_to_mentor = True
        self.user1.is_email_verified = True
        self.user2.need_mentoring = True
        self.user2.is_email_verified = True

        db.session.add(self.user1)
        db.session.add(self.user2)
        db.session.commit()
    def setUp(self):
        super(TestMentorshipRelationDeleteDAO, self).setUp()

        self.first_user = UserModel(
            name=user1["name"],
            email=user1["email"],
            username=user1["username"],
            password=user1["password"],
            terms_and_conditions_checked=user1["terms_and_conditions_checked"],
        )
        self.second_user = UserModel(
            name=user2["name"],
            email=user2["email"],
            username=user2["username"],
            password=user2["password"],
            terms_and_conditions_checked=user2["terms_and_conditions_checked"],
        )

        # making sure both are available to be mentor or mentee
        self.first_user.need_mentoring = True
        self.first_user.available_to_mentor = True
        self.first_user.is_email_verified = True
        self.second_user.need_mentoring = True
        self.second_user.available_to_mentor = True
        self.second_user.is_email_verified = True

        self.notes_example = "description of a good mentorship relation"

        self.now_datetime = datetime.now()
        self.end_date_example = self.now_datetime + timedelta(weeks=5)

        db.session.add(self.first_user)
        db.session.add(self.second_user)
        db.session.commit()

        # create new mentorship relation

        self.mentorship_relation = MentorshipRelationModel(
            action_user_id=self.first_user.id,
            mentor_user=self.first_user,
            mentee_user=self.second_user,
            creation_date=self.now_datetime.timestamp(),
            end_date=self.end_date_example.timestamp(),
            state=MentorshipRelationState.PENDING,
            notes=self.notes_example,
            tasks_list=TasksListModel(),
        )

        db.session.add(self.mentorship_relation)
        db.session.commit()
Beispiel #8
0
 def update_preferred_location(firebase_id: str, data: Dict[str, str]):
     state = data['state']
     district = data['district']
     if "sub_district" in data:
         sub_district = data["sub_district"]
     else:
         sub_district = ""
     if "area" in data:
         area = data["area"]
     else:
         area = ""
     try:
         user = UserModel.find_by_firebase_id(firebase_id)
     
     except Exception as e:
         return messages.CANNOT_FIND_USER, 400
     
     if user.is_donor:
         preferred_location = user.preferred_location
         if preferred_location:
             preferred_location.state = state
             preferred_location.district = district
             preferred_location.sub_district = sub_district
             preferred_location.area = area
             preferred_location.save_to_db()
         else:
             updated_location = PreferredLocationModel(user.id, state, district, sub_district, area)
             updated_location.save_to_db()
         return {"message": "Preferred location updated successfully"}, 200
     else:
         return {"message": "This user cannot set preferred location"}, 401
Beispiel #9
0
    def test_update_username_not_taken(self):

        self.first_user = UserModel(
            name=user1["name"],
            email=user1["email"],
            username=user1["username"],
            password=user1["password"],
            terms_and_conditions_checked=user1["terms_and_conditions_checked"],
        )
        self.first_user.is_email_verified = True

        db.session.add(self.first_user)
        db.session.commit()

        user1_new_username = "******"
        auth_header = get_test_request_header(self.first_user.id)
        expected_response = messages.USER_SUCCESSFULLY_UPDATED
        actual_response = self.client.put(
            "/user",
            follow_redirects=True,
            headers=auth_header,
            data=json.dumps(dict(username=user1_new_username)),
            content_type="application/json",
        )

        self.assertEqual(200, actual_response.status_code)
        self.assertDictEqual(expected_response,
                             json.loads(actual_response.data))
        self.assertEqual(user1_new_username, self.first_user.username)
Beispiel #10
0
    def test_update_username_already_taken(self):

        self.first_user = UserModel(
            name=user1["name"],
            email=user1["email"],
            username=user1["username"],
            password=user1["password"],
            terms_and_conditions_checked=user1["terms_and_conditions_checked"],
        )
        self.first_user.is_email_verified = True

        db.session.add(self.first_user)
        db.session.commit()

        auth_header = get_test_request_header(self.first_user.id)
        expected_response = messages.USER_USES_A_USERNAME_THAT_ALREADY_EXISTS
        actual_response = self.client.put(
            "/user",
            follow_redirects=True,
            headers=auth_header,
            data=json.dumps(dict(username=self.admin_user.username)),
            content_type="application/json",
        )

        self.assertEqual(400, actual_response.status_code)
        self.assertDictEqual(expected_response,
                             json.loads(actual_response.data))
Beispiel #11
0
    def create_task(user_id: int, mentorship_relation_id: int, data: Dict[str, str]):
        """Creates a new task.

        Creates a new task in a mentorship relation if the specified user is already involved in it.

        Args:
            user_id: The id of the user.
            mentorship_relation_id: The id of the mentorship relation.
            data: A list containing the description of the task.

        Returns:
            A two element list where the first element is a dictionary containing a key 'message' indicating
            in its value if the task creation was successful or not as a string. The last element is the HTTP
            response code.
        """

        description = data["description"]

        user = UserModel.find_by_id(user_id)
        relation = MentorshipRelationModel.find_by_id(_id=mentorship_relation_id)
        if relation is None:
            return messages.MENTORSHIP_RELATION_DOES_NOT_EXIST, HTTPStatus.NOT_FOUND

        if relation.state != MentorshipRelationState.ACCEPTED:
            return messages.UNACCEPTED_STATE_RELATION, HTTPStatus.FORBIDDEN

        if (relation.mentor_id != user_id) and (relation.mentee_id != user_id):
            return messages.USER_NOT_INVOLVED_IN_THIS_MENTOR_RELATION, 403

        now_timestamp = datetime.now().timestamp()
        relation.tasks_list.add_task(description=description, created_at=now_timestamp)
        relation.tasks_list.save_to_db()

        return messages.TASK_WAS_CREATED_SUCCESSFULLY, HTTPStatus.CREATED
Beispiel #12
0
    def close_application(firebase_id: str, reserved_application_id: int):
        try:
            user = UserModel.find_by_firebase_id(firebase_id)
        except Exception as e:
            return messages.CANNOT_FIND_USER, 400

        if not user.is_donor:
            return {"message": "This user cannot close the application"}, 200

        application = ReservedApplicationModel.find_by_id(
            reserved_application_id)

        if application and application.donor == user:
            if application.donation_date == None:
                original_applcation = ApplicationModel.find_by_id(
                    application.application_id)
                original_applcation.remaining_amount = original_applcation.remaining_amount + application.amount
                original_applcation.donor.remove(user)
                original_applcation.save_to_db()
                # Not a good practice, if we need to check which donor is culprit and just wasting time of moderator and recipient
                application.delete_from_db()
                return {"message": "Application is removed and updated"}, 200
            else:
                application.is_active = False
                original_applcation = ApplicationModel.find_by_id(
                    application.application_id)
                original_applcation.donor.remove(user)
                original_applcation.save_to_db()
                application.save_to_db()
                return {"message": "Application is closed"}, 200
        else:
            return {
                "message": "Cannot find reserved application for this user"
            }, 404
Beispiel #13
0
    def test_dao_confirm_registration_bad_token(self):
        dao = UserDAO()

        user = UserModel(
            name=user2["name"],
            email=user2["email"],
            username=user2["username"],
            password=user2["password"],
            terms_and_conditions_checked=user2["terms_and_conditions_checked"],
        )
        db.session.add(user)
        db.session.commit()

        # Verify that user was inserted in database through DAO
        user = UserModel.query.filter_by(email=user2["email"]).first()
        self.assertIsNotNone(user)

        # bad token because it is incomplete
        bad_token = generate_confirmation_token(user2["email"])[:4]

        self.assertFalse(user.is_email_verified)

        actual_result = dao.confirm_registration(bad_token)

        self.assertFalse(user.is_email_verified)
        self.assertIsNone(user.email_verification_date)
        self.assertEqual((messages.EMAIL_EXPIRED_OR_TOKEN_IS_INVALID, 400),
                         actual_result)
Beispiel #14
0
    def test_update_availability_to_be_mentee_to_false(self):

        self.first_user = UserModel(
            name=user1["name"],
            email=user1["email"],
            username=user1["username"],
            password=user1["password"],
            terms_and_conditions_checked=user1["terms_and_conditions_checked"],
        )
        self.first_user.is_email_verified = True
        self.first_user.need_mentoring = True

        db.session.add(self.first_user)
        db.session.commit()

        expected_response = messages.USER_SUCCESSFULLY_UPDATED
        test_need_mentoring = False
        auth_header = get_test_request_header(self.first_user.id)

        self.assertEqual(True, self.first_user.need_mentoring)

        actual_response = self.client.put(
            "/user",
            follow_redirects=True,
            headers=auth_header,
            data=json.dumps(dict(need_mentoring=test_need_mentoring)),
            content_type="application/json",
        )

        self.assertEqual(200, actual_response.status_code)
        self.assertDictEqual(expected_response,
                             json.loads(actual_response.data))
        self.assertEqual(test_need_mentoring, self.first_user.need_mentoring)
    def delete_request(user_id: int, request_id: int):
        """Deletes a mentorship request.

        Deletes a mentorship request if the current user was the one who created it and the request is in the pending state.

        Args:
            user_id: ID of the user that is deleting a request.
            request_id: ID of the request.

        Returns:
            message: A message corresponding to the completed action; success if mentorship relation request is deleted, failure if otherwise.
        """

        user = UserModel.find_by_id(user_id)
        request = MentorshipRelationModel.find_by_id(request_id)

        # verify if request exists
        if request is None:
            return messages.MENTORSHIP_RELATION_REQUEST_DOES_NOT_EXIST, HTTPStatus.NOT_FOUND

        # verify if request is in pending state
        if request.state != MentorshipRelationState.PENDING:
            return messages.NOT_PENDING_STATE_RELATION, HTTPStatus.BAD_REQUEST

        # verify if user created the mentorship request
        if request.action_user_id != user_id:
            return messages.CANT_DELETE_UNINVOLVED_REQUEST, HTTPStatus.BAD_REQUEST

        # All was checked
        request.delete_from_db()

        return messages.MENTORSHIP_RELATION_WAS_DELETED_SUCCESSFULLY, HTTPStatus.OK
    def confirm_registration(token: str):
        """ Determines whether a user's email registration has been confirmed.

        Determines whether a user's email registration was invalid, previously confirmed, or just confirmed.

        Arguments:
            token: Serialized and signed email address as a URL safe string.

        Returns:
            A message that indicates if the confirmation was invalid, already happened, or just happened, and the HTTP response code.

        """

        email_from_token = confirm_token(token)

        if not email_from_token or email_from_token is None:
            return messages.EMAIL_EXPIRED_OR_TOKEN_IS_INVALID, HTTPStatus.BAD_REQUEST

        user = UserModel.find_by_email(email_from_token)
        if user.is_email_verified:
            return messages.ACCOUNT_ALREADY_CONFIRMED, HTTPStatus.OK
        else:
            user.is_email_verified = True
            user.email_verification_date = datetime.now()
            user.save_to_db()
            return messages.ACCOUNT_ALREADY_CONFIRMED_AND_THANKS, HTTPStatus.OK
    def reject_request(user_id: int, request_id: int):
        """Rejects a mentorship request.

        Args:
            user_id: ID of the user rejecting the request.
            request_id: ID of the request to be rejected.

        Returns:
            message: A message corresponding to the completed action; success if mentorship relation request is rejected, failure if otherwise.
        """

        user = UserModel.find_by_id(user_id)
        request = MentorshipRelationModel.find_by_id(request_id)

        # verify if request exists
        if request is None:
            return messages.MENTORSHIP_RELATION_REQUEST_DOES_NOT_EXIST, HTTPStatus.NOT_FOUND

        # verify if request is in pending state
        if request.state != MentorshipRelationState.PENDING:
            return messages.NOT_PENDING_STATE_RELATION, HTTPStatus.BAD_REQUEST

        # verify if I'm the receiver of the request
        if request.action_user_id == user_id:
            return messages.USER_CANT_REJECT_REQUEST_SENT_BY_USER, HTTPStatus.BAD_REQUEST

        # verify if I'm involved in this relation
        if not (request.mentee_id == user_id or request.mentor_id == user_id):
            return messages.CANT_REJECT_UNINVOLVED_RELATION_REQUEST, HTTPStatus.BAD_REQUEST

        # All was checked
        request.state = MentorshipRelationState.REJECTED
        request.save_to_db()

        return messages.MENTORSHIP_RELATION_WAS_REJECTED_SUCCESSFULLY, HTTPStatus.OK
    def cancel_relation(user_id: int, relation_id: int):
        """Allows a given user to terminate a particular relationship.

        Args:
            user_id: ID of the user terminating the relationship.
            relation_id: ID of the relationship.

        Returns:
            message: A message corresponding to the completed action; success if mentorship relation is terminated, failure if otherwise.
        """

        user = UserModel.find_by_id(user_id)
        request = MentorshipRelationModel.find_by_id(relation_id)

        # verify if request exists
        if request is None:
            return messages.MENTORSHIP_RELATION_REQUEST_DOES_NOT_EXIST, HTTPStatus.NOT_FOUND

        # verify if request is in pending state
        if request.state != MentorshipRelationState.ACCEPTED:
            return messages.UNACCEPTED_STATE_RELATION, HTTPStatus.BAD_REQUEST

        # verify if I'm involved in this relation
        if not (request.mentee_id == user_id or request.mentor_id == user_id):
            return messages.CANT_CANCEL_UNINVOLVED_REQUEST, HTTPStatus.BAD_REQUEST

        # All was checked
        request.state = MentorshipRelationState.CANCELLED
        request.save_to_db()

        return messages.MENTORSHIP_RELATION_WAS_CANCELLED_SUCCESSFULLY, HTTPStatus.OK
Beispiel #19
0
 def get_histroy(firebase_id: str):
     try:
         user = UserModel.find_by_firebase_id(firebase_id)
     except Exception as e:
         return messages.CANNOT_FIND_USER, 400
     
     role = 0 if user.is_donor else 1 if user.is_recipient else 2
     
     reserved_applications = list()
     
     if user.is_donor:
         reserved_applications = user.reserved_as_donor
     elif user.is_moderator:
         reserved_applications = user.reserved_as_moderator
     else:
         applications = user.application
         
         for app in applications:
             reserved_applications = app.reserved
             
     application_list = list()
     for reserved in reserved_applications:
         if reserved.is_active == False:
             application = ApplicationModel.find_by_id(reserved.application_id)
             application_data = application.json()
             history_application = dict()
             history_application["recipient_name"] = application_data["applicant_first_name"] + " " + application_data["applicant_last_name"]
             history_application["moderator_name"] = reserved.moderator.name
             history_application["donor_name"] = reserved.donor.name
             history_application["amount"] = reserved.amount
             history_application["donation_date"] = reserved.donation_date
             application_list.append(history_application)
             
     return {"role": role, 
         "history": application_list }, 200
    def accept_request(user_id: int, request_id: int):
        """Allows a mentorship request.

        Args:
            user_id: ID of the user accepting the request.
            request_id: ID of the request to be accepted.

        Returns:
            message: A message corresponding to the completed action; success if mentorship relation request is accepted, failure if otherwise.
        """

        user = UserModel.find_by_id(user_id)
        request = MentorshipRelationModel.find_by_id(request_id)

        # verify if request exists
        if request is None:
            return messages.MENTORSHIP_RELATION_REQUEST_DOES_NOT_EXIST, HTTPStatus.NOT_FOUND

        # verify if request is in pending state
        if request.state != MentorshipRelationState.PENDING:
            return messages.NOT_PENDING_STATE_RELATION, HTTPStatus.BAD_REQUEST

        # verify if I'm the receiver of the request
        if request.action_user_id == user_id:
            return messages.CANT_ACCEPT_MENTOR_REQ_SENT_BY_USER, HTTPStatus.BAD_REQUEST

        # verify if I'm involved in this relation
        if not (request.mentee_id == user_id or request.mentor_id == user_id):
            return messages.CANT_ACCEPT_UNINVOLVED_MENTOR_RELATION, HTTPStatus.BAD_REQUEST

        my_requests = user.mentee_relations + user.mentor_relations

        # verify if I'm on a current relation
        for my_request in my_requests:
            if my_request.state == MentorshipRelationState.ACCEPTED:
                return messages.USER_IS_INVOLVED_IN_A_MENTORSHIP_RELATION, HTTPStatus.BAD_REQUEST

        mentee = request.mentee
        mentor = request.mentor

        # If I am mentor : Check if the mentee isn't in any other relation already
        if user_id == mentor.id:
            mentee_requests = mentee.mentee_relations + mentee.mentor_relations

            for mentee_request in mentee_requests:
                if mentee_request.state == MentorshipRelationState.ACCEPTED:
                    return messages.MENTEE_ALREADY_IN_A_RELATION, HTTPStatus.BAD_REQUEST
        # If I am mentee : Check if the mentor isn't in any other relation already
        else:
            mentor_requests = mentor.mentee_relations + mentor.mentor_relations

            for mentor_request in mentor_requests:
                if mentor_request.state == MentorshipRelationState.ACCEPTED:
                    return messages.MENTOR_ALREADY_IN_A_RELATION, HTTPStatus.BAD_REQUEST

        # All was checked
        request.state = MentorshipRelationState.ACCEPTED
        request.save_to_db()

        return messages.MENTORSHIP_RELATION_WAS_ACCEPTED_SUCCESSFULLY, HTTPStatus.OK
Beispiel #21
0
    def delete_task(user_id: int, mentorship_relation_id: int, task_id: int):
        """Deletes a specified task from a mentorship relation.

        Deletes a task that belongs to a user who is involved in the specified
        mentorship relation.

        Args:
            user_id: The id of the user.
            mentorship_relation_id: The id of the mentorship relation.
            task_id: The id of the task.

        Returns:
            A two element list where the first element is a dictionary containing a key 'message' indicating in its value if the
            task was deleted successfully or not as a string. The last element is the HTTP response code.
        """

        user = UserModel.find_by_id(user_id)
        relation = MentorshipRelationModel.find_by_id(mentorship_relation_id)
        if relation is None:
            return messages.MENTORSHIP_RELATION_DOES_NOT_EXIST, HTTPStatus.NOT_FOUND

        task = relation.tasks_list.find_task_by_id(task_id)
        if task is None:
            return messages.TASK_DOES_NOT_EXIST, HTTPStatus.NOT_FOUND

        if not (user_id == relation.mentee_id or user_id == relation.mentor_id):
            return messages.USER_NOT_INVOLVED_IN_THIS_MENTOR_RELATION, HTTPStatus.UNAUTHORIZED

        relation.tasks_list.delete_task(task_id)

        return messages.TASK_WAS_DELETED_SUCCESSFULLY, HTTPStatus.OK
Beispiel #22
0
    def list_tasks(user_id: int, mentorship_relation_id: int):
        """Retrieves all tasks of a user in a mentorship relation.

        Lists all tasks from a mentorship relation for the specified user if the user is involved in a current mentorship relation.

        Args:
            user_id: The id of the user.
            mentorship_relation_id: The id of the mentorship relation.

        Returns:
            A list containing all the tasks one user has in a mentorship relation. otherwise, it returns a two element list where the first element is
            a dictionary containing a key 'message' indicating in its value if there were any problem finding user's tasks in the specified
            mentorship relation as a string. The last element is the HTTP response code
        """

        user = UserModel.find_by_id(user_id)
        relation = MentorshipRelationModel.find_by_id(mentorship_relation_id)
        if relation is None:
            return messages.MENTORSHIP_RELATION_DOES_NOT_EXIST, HTTPStatus.NOT_FOUND

        if not (user_id == relation.mentee_id or user_id == relation.mentor_id):
            return messages.USER_NOT_INVOLVED_IN_THIS_MENTOR_RELATION, HTTPStatus.UNAUTHORIZED

        all_tasks = relation.tasks_list.tasks

        return all_tasks
Beispiel #23
0
    def test_change_password_to_current_password(self):
        self.first_user = UserModel(
            name=user1["name"],
            email=user1["email"],
            username=user1["username"],
            password=user1["password"],
            terms_and_conditions_checked=user1["terms_and_conditions_checked"],
        )
        self.first_user.is_email_verified = True
        self.first_user.need_mentoring = True

        db.session.add(self.first_user)
        db.session.commit()

        auth_header = get_test_request_header(self.first_user.id)
        expected_response = messages.USER_ENTERED_CURRENT_PASSWORD
        actual_response = self.client.put(
            "/user/change_password",
            follow_redirects=True,
            headers=auth_header,
            data=json.dumps(
                dict(current_password=user1["password"],
                     new_password=user1["password"])),
            content_type="application/json",
        )

        self.assertEqual(400, actual_response.status_code)
        self.assertDictEqual(expected_response,
                             json.loads(actual_response.data))
    def get_user_statistics(user_id: int):
        """Shows some basic user statistics

        Gets the following statistics of the user:
        -> Pending Requests
        -> Accepted Requests
        -> Rejected Requests
        -> Completed Relations
        -> Cancelled Relations
        -> Up to 3 recent achievements

        Args:
            user_id: The id of the user for whom stats are requested

        Returns:
            A dict containing the stats (if the user ID is valid)
            If user ID is invalid, returns None
        """
        user = UserModel.find_by_id(user_id)

        if not user:
            return None

        all_relations = user.mentor_relations + user.mentee_relations
        (
            pending_requests,
            accepted_requests,
            rejected_requests,
            completed_relations,
            cancelled_relations,
        ) = (0, 0, 0, 0, 0)
        for relation in all_relations:
            if relation.state == MentorshipRelationState.PENDING:
                pending_requests += 1
            elif relation.state == MentorshipRelationState.ACCEPTED:
                accepted_requests += 1
            elif relation.state == MentorshipRelationState.REJECTED:
                rejected_requests += 1
            elif relation.state == MentorshipRelationState.COMPLETED:
                completed_relations += 1
            elif relation.state == MentorshipRelationState.CANCELLED:
                cancelled_relations += 1

        achievements = UserDAO.get_achievements(user_id)
        if achievements:
            # We only need the first three of these achievements
            achievements = achievements[0:3]
            sorted(achievements, key=itemgetter("created_at"))

        response = {
            "name": user.name,
            "pending_requests": pending_requests,
            "accepted_requests": accepted_requests,
            "rejected_requests": rejected_requests,
            "completed_relations": completed_relations,
            "cancelled_relations": cancelled_relations,
            "achievements": achievements,
        }
        return response
Beispiel #25
0
    def test_get_achievements(self):
        dao = UserDAO()

        mentor = UserModel("Test mentor", "test_mentor", "test_password",
                           "*****@*****.**", True)

        mentee = UserModel("Test mentee", "test_mentee", "test_password",
                           "*****@*****.**", True)

        mentor.is_email_verified = True
        mentor.available_to_mentor = True
        mentee.is_email_verified = True
        mentee.need_mentoring = True

        db.session.add(mentor)
        db.session.add(mentee)
        db.session.commit()

        start_date = datetime.datetime.now()
        end_date = start_date + datetime.timedelta(weeks=4)

        tasks_list = TasksListModel()
        tasks_list.add_task(
            description="Test Task",
            created_at=start_date.timestamp(),
            is_done=True,
            completed_at=end_date.timestamp(),
        )
        tasks_list.add_task(
            description="Test Task 2",
            created_at=start_date.timestamp(),
            is_done=True,
            completed_at=end_date.timestamp(),
        )

        relation = MentorshipRelationModel(
            action_user_id=mentee.id,
            mentor_user=mentor,
            mentee_user=mentee,
            creation_date=start_date.timestamp(),
            end_date=end_date.timestamp(),
            state=MentorshipRelationState.ACCEPTED,
            tasks_list=tasks_list,
            notes="Test Notes",
        )

        db.session.add(tasks_list)
        db.session.add(relation)
        db.session.commit()

        achievements = dao.get_achievements(mentee.id)

        self.assertEqual(2, len(achievements))

        for achievement in achievements:
            self.assertTrue(achievement.get("is_done"))
Beispiel #26
0
    def setUp(self):
        db.create_all()

        self.first_user = UserModel(
            name=user1["name"],
            email=user1["email"],
            username=user1["username"],
            password=user1["password"],
            terms_and_conditions_checked=user1["terms_and_conditions_checked"],
        )
        self.second_user = UserModel(
            name=user2["name"],
            email=user2["email"],
            username=user2["username"],
            password=user2["password"],
            terms_and_conditions_checked=user2["terms_and_conditions_checked"],
        )

        self.notes_example = "description of a good mentorship relation"

        now_datetime = datetime.now()
        self.start_date_example = datetime(year=now_datetime.year + 1,
                                           month=3,
                                           day=1).timestamp()
        self.end_date_example = datetime(year=now_datetime.year + 1,
                                         month=5,
                                         day=1).timestamp()
        self.now_datetime = datetime.now().timestamp()

        db.session.add(self.first_user)
        db.session.add(self.second_user)
        db.session.commit()

        self.mentorship_relation = MentorshipRelationModel(
            action_user_id=self.first_user.id,
            mentor_user=self.first_user,
            mentee_user=self.second_user,
            creation_date=self.now_datetime,
            end_date=self.end_date_example,
            state=MentorshipRelationState.PENDING,
            notes=self.notes_example,
            tasks_list=TasksListModel(),
        )
        db.session.add(self.mentorship_relation)
        db.session.commit()
Beispiel #27
0
    def test_dao_assign_admin_role_to_admin_user(self):

        dao = AdminDAO()

        user = UserModel(
            name=user1["name"],
            username=user1["username"],
            email=user1["email"],
            password=user1["password"],
            terms_and_conditions_checked=user1["terms_and_conditions_checked"],
        )

        user.save_to_db()

        user = UserModel.query.filter_by(id=2).first()
        self.assertFalse(user.is_admin)
        user.is_admin = True
        user.save_to_db()
        self.assertTrue(user.is_admin)

        data = dict(user_id=2)

        dao_result = dao.assign_new_user(1, data)

        self.assertEqual((messages.USER_IS_ALREADY_AN_ADMIN, 400), dao_result)
Beispiel #28
0
 def dashboard(firebase_id: str):
     try:
         user = UserModel.find_by_firebase_id(firebase_id)
     except Exception as e:
         return messages.CANNOT_FIND_USER, 400
     
     role = "donor" if user.is_donor else "recipient" if user.is_recipient else "moderator"
     
     return {"message": role}, 200
    def setUp(self):
        super(TestListAdminUsersApi, self).setUp()

        self.admin_user_2 = UserModel(
            name=test_admin_user_2["name"],
            email=test_admin_user_2["email"],
            username=test_admin_user_2["username"],
            password=test_admin_user_2["password"],
            terms_and_conditions_checked=test_admin_user_2[
                "terms_and_conditions_checked"
            ],
        )

        self.admin_user_3 = UserModel(
            name=test_admin_user_3["name"],
            email=test_admin_user_3["email"],
            username=test_admin_user_3["username"],
            password=test_admin_user_3["password"],
            terms_and_conditions_checked=test_admin_user_3[
                "terms_and_conditions_checked"
            ],
        )

        self.normal_user_1 = UserModel(
            name=user1["name"],
            email=user1["email"],
            username=user1["username"],
            password=user1["password"],
            terms_and_conditions_checked=user1["terms_and_conditions_checked"],
        )

        # creating 3 admin users(first admin user created by basetestcase setup) and 1 normal user
        self.admin_user_2.is_email_verified = True
        self.admin_user_3.is_email_verified = True
        self.normal_user_1.is_email_verified = True

        self.admin_user_2.is_admin = True
        self.admin_user_3.is_admin = True
        self.normal_user_1.is_admin = False

        db.session.add(self.admin_user_2)
        db.session.add(self.admin_user_3)
        db.session.add(self.normal_user_1)
        db.session.commit()
Beispiel #30
0
 def update_profile_image(firebase_id: str, image_url: str):
     
     try:
         user = UserModel.find_by_firebase_id(firebase_id)
     except Exception as e:
         return messages.CANNOT_FIND_USER, 400
     
     user.profile_image = image_url
     user.save_to_db()
     
     return {"message": "Image updated successfully"}, 200