Beispiel #1
0
        public IActionResult CreateRating(int itemId, [FromBody] RatingForCreationDto rating)
        {
            if (rating.Description == rating.Name)
            {
                ModelState.AddModelError("Description", "The provided description should be different from the name.");
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var item = ItemsDataStore.Current.Items.FirstOrDefault(x => x.Id == itemId);

            if (item == null)
            {
                return(NotFound());
            }

            var newId = ItemsDataStore.Current.Items.SelectMany(x => x.Rating).Max(r => r.Id);

            var finalRate = new RatingDto()
            {
                Id          = newId,
                Name        = rating.Name,
                Description = rating.Description
            };

            item.Rating.Add(finalRate);

            return(CreatedAtRoute(
                       "GetItemRating",
                       new { itemId, id = finalRate.Id }, finalRate));
        }
        public async Task RateUser_Authenticated_UnexsistingRatedUser_ShouldReturnNotFound(
            string unexistingUserName)
        {
            // Arrange
            var ratingUser = db.UserRepository.Get(1);

            if (ratingUser == null)
            {
                throw new Exception(noSampleUser);
            }

            var ratedUser = db.UserRepository.Get(unexistingUserName);

            if (ratedUser != null)
            {
                throw new ArgumentNullException("User did exist, " +
                                                "please change the username for the non existing testing user.");
            }

            var rating = new RatingForCreationDto()
            {
                UserName = unexistingUserName, Value = 2
            };

            var token = FakeToken.CreateFakeTokenByUser(ratingUser);

            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);


            // Act
            var response = await _client.PutAsJsonAsync("rate", rating);

            // Assert
            response.StatusCode.Should().Be(HttpStatusCode.NotFound);
        }
Beispiel #3
0
        public async Task <IActionResult> RateUserAsync(RatingForCreationDto rating)
        {
            var userToRate = await _userRepository.GetAsync(rating.UserId);

            if (userToRate == null)
            {
                return(NotFound());
            }

            // maps the RatedUserId and value
            var ratingEntity = _mapper.Map <Rating>(rating);

            // maps the RatingUserId
            string userName = User.Identity.Name;
            string userId   = _commentRepository.GetUserIdFromUserName(userName);

            ratingEntity.RatingUserId = userId;
            if (userId == rating.UserId)
            {
                return(StatusCode(500, new Response {
                    Status = "Error", Message = "Users can not rate themselves"
                }));
            }

            // adds the new entity to the database and saves it
            _ratingRepository.Add(ratingEntity);
            _ratingRepository.Save();

            return(Ok());
        }
        public async Task RateUser_Authenticated_ExsistingUsers_ShouldCreateRating()
        {
            // Arrange
            var ratingUser = db.UserRepository.Get(1);
            var ratedUser  = db.UserRepository.Get(2);

            if (ratingUser == null || ratedUser == null)
            {
                throw new Exception(noSampleUser);
            }

            var oldRating = db.RatingRepository.Get(ratedUser.Id, ratingUser.Id);
            int?oldScore  = oldRating == null ? null : oldRating.Score as int?;

            var rating = new RatingForCreationDto()
            {
                UserName = ratedUser.UserName, Value = 2
            };

            var token = FakeToken.CreateFakeTokenByUser(ratingUser);

            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            try
            {
                // Act
                var response = await _client.PutAsJsonAsync("rate", rating);

                // Assert
                response.StatusCode.Should().Be(HttpStatusCode.OK);
                var addedRating = db.RatingRepository.Get(ratedUser.Id, ratingUser.Id);
                addedRating.Should().NotBeNull();
                addedRating.Score.Should().Be(rating.Value);
            }
            // Finally to ensure that the test-cleanup is always executed
            finally
            {
                // Cleanup incase of test failure
                RemoveRatingFromDb(ratedUser.Id, ratingUser.Id, oldScore);
                this.Dispose();
            }
        }
Beispiel #5
0
        public async Task <ActionResult> GiveRate([FromBody] RatingForCreationDto ratingForCreationDto)
        {
            var userSourceRate = await _userRepo.GetUserByUserClaims(HttpContext.User);

            if (userSourceRate == null)
            {
                return(Unauthorized("User is Unauthorized"));
            }

            var userDestinationRate = await _userRepo.GetUserByUsername(ratingForCreationDto.Username);

            if (userDestinationRate == null)
            {
                return(BadRequest("User Not Found"));
            }
            if (userSourceRate.Id == userDestinationRate.Id)
            {
                return(BadRequest("You Can't Rate Yourself"));
            }
            var resultRemoveOldRate =
                await _ratingRepo.RemoveOldRateIfExists(userSourceRate.Id, userDestinationRate.Id);

            if (resultRemoveOldRate == false)
            {
                return(BadRequest("Error Occured While Removing Old Rate"));
            }
            var newUserRate = new Rating
            {
                UserSourceRateId      = userSourceRate.Id,
                UserDestinationRateId = userDestinationRate.Id,
                Star = (RatingStar)(ratingForCreationDto.Value - 1),
            };
            var result = await _ratingRepo.GiveRate(newUserRate);

            if (result)
            {
                return(Ok((new { message = "Setting new rate done successfully" })));
            }
            throw new Exception("Error Occured While Setting New Rate.");
        }
        public async Task <ActionResult> RateUser(RatingForCreationDto rating)
        {
            var ratedUser = _unitOfWork.UserRepository.Get(rating.UserName);

            if (ratedUser == null)
            {
                ApiErrorResponseBody errorResponse = new ApiErrorResponseBody(false);
                errorResponse.AddError("User", new string[] { $"Could not found a user with name {rating.UserName}" });
                return(NotFound(errorResponse));
            }

            var ratingUser = await _userManager.GetUserAsync(User);

            if (ratingUser.Id == ratedUser.Id)
            {
                ApiErrorResponseBody errorResponse = new ApiErrorResponseBody(false);
                errorResponse.AddError("IllicitRating", new string[] { "A user can't give itself a rating" });
                return(BadRequest(errorResponse));
            }

            var foundRating = _unitOfWork.RatingRepository.Get(ratedUser.Id, ratingUser.Id);

            if (foundRating == null)
            {
                var ratingToAdd = _mapper.Map <Rating>(rating);
                ratingToAdd.RatingUserId = ratingUser.Id;
                ratingToAdd.RatedUserId  = ratedUser.Id;
                _unitOfWork.RatingRepository.Add(ratingToAdd);
            }
            else
            {
                foundRating.Score = rating.Value;
            }

            _unitOfWork.SaveChanges();

            return(Ok());
        }
        public async Task RateUser_Unauthenticated_ExistingUsers_ShouldReturnUnauthorized()
        {
            // Arrange
            var ratingUser = db.UserRepository.Get(1);
            var ratedUser  = db.UserRepository.Get(2);

            if (ratingUser == null || ratedUser == null)
            {
                throw new ArgumentNullException(noSampleUser);
            }

            var oldRating = db.RatingRepository.Get(ratedUser.Id, ratingUser.Id);
            int?oldScore  = oldRating == null ? null : oldRating.Score as int?;

            var rating = new RatingForCreationDto()
            {
                UserName = ratedUser.UserName, Value = 2
            };

            try
            {
                // Act
                var response = await _client.PutAsJsonAsync("rate", rating);

                // Assert
                response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
                var addedRating = db.RatingRepository.Get(ratedUser.Id, ratingUser.Id);
                addedRating?.Score.Should().Be(oldScore);
            }
            // Finally to ensure that the test-cleanup is always executed
            finally
            {
                // Cleanup incase of test failure
                RemoveRatingFromDb(ratedUser.Id, ratingUser.Id, oldScore);
                this.Dispose();
            }
        }