public async Task RegisterAsync(RegistrationDTO registrationDTO)
        {
            ValidationResults result = ModelValidator.IsValid(registrationDTO);

            if (!result.Successed)
            {
                throw ValidationExceptionBuilder.BuildValidationException(result);
            }

            User newUser = new Guest()
            {
                FirstName = registrationDTO.FirstName,
                LastName  = registrationDTO.LastName,
                Email     = registrationDTO.Email,
                UserName  = registrationDTO.Email,
                Passport  = registrationDTO.Passport
            };

            string password = registrationDTO.Password;

            await CheckIfThePasswordIsValid(password);
            await CheckIfTheUserDoesNotExist(newUser);

            var isCreated = await _userManager.CreateAsync(newUser, password);

            if (!isCreated.Succeeded)
            {
                throw new DBException("Cann't create new user");
            }
            var isAddedToRole = await _userManager.AddToRoleAsync(newUser, "user");

            if (!isAddedToRole.Succeeded)
            {
                throw new DBException("Cann't add new user to user's role");
            }

            var code = await _userManager.GenerateEmailConfirmationTokenAsync(newUser);

            string message = "Ваш код пiдтвердження: " + code;
            await EmailService.SendEmailAsync(newUser.Email, "HotelLocker пiдтвердження паролю", message);
        }
        public async Task <ReservationDTO> EditReservation(ReservationEditDTO reservationEditDTO, int userId)
        {
            ValidationResults result = ModelValidator.IsValid(reservationEditDTO);

            if (!result.Successed)
            {
                throw ValidationExceptionBuilder.BuildValidationException(result);
            }

            var reservation = context.Reservations.Get(reservationEditDTO.Id);

            if (reservation == null)
            {
                throw new NotFoundException("No such reservation");
            }

            if (reservation.GuestId != userId)
            {
                throw new PermissionException();
            }
            if (reservationEditDTO.StartDate != null && reservationEditDTO.EndDate != null)
            {
                bool canBeReserved = context.Reservations.GetAll()
                                     .Where(r => r.RoomId == reservation.RoomId && r.Id != reservation.Id && (r.StartDate <reservationEditDTO.StartDate && r.EndDate> reservationEditDTO.StartDate) || (r.StartDate <reservationEditDTO.EndDate && r.EndDate> reservationEditDTO.EndDate))
                                     .Count() == 0;
                if (!canBeReserved)
                {
                    throw new ValidationException("Room is not available is this time");
                }
                reservation.StartDate = reservationEditDTO.StartDate;
                reservation.EndDate   = reservationEditDTO.EndDate;
            }
            if (!string.IsNullOrEmpty(reservationEditDTO.AdditionalInfo))
            {
                reservation.AdditionalInfo = reservationEditDTO.AdditionalInfo;
            }
            context.Reservations.Update(reservation);
            await context.SaveAsync();

            return(reservation.ToReservationDTO());
        }
Beispiel #3
0
        private async Task <bool> FormPromptValidatorAsync(PromptValidatorContext <string> promptContext, CancellationToken cancellationToken)
        {
            var valid = false;

            if (promptContext.Recognized.Succeeded)
            {
                if (promptContext.Recognized.Value.IsJsonSchema())
                {
                    var form = JsonConvert.DeserializeObject <UserCompanyDTO>(promptContext.Recognized.Value);

                    var result = ModelValidator.IsValid(form);

                    if (!result.HasError)
                    {
                        valid = true;
                    }
                }
            }

            return(await Task.FromResult(valid));
        }
Beispiel #4
0
        public void Good_Post_Create()
        {
            // Arrange
            var newsViewModel = new NewsViewModel()
            {
                AddedDate = DateTime.Now,
                Position  = 1,
                Title     = "New",
                Content   = "Quisque nulla nunc, tempor eu lorem non, pharetra laoreet massa."
            };
            var news = new News()
            {
                AddedDate = DateTime.Now,
                Position  = 1,
                Title     = "New",
                Content   = "Quisque nulla nunc, tempor eu lorem non, pharetra laoreet massa."
            };
            var validator  = new ModelValidator <NewsViewModel>(newsViewModel);
            var service    = Substitute.For <INewsRepository>();
            var mapper     = Substitute.For <IMapper>();
            var controller = new NewsController(service, mapper);

            mapper.Map <NewsViewModel, News>(newsViewModel).Returns(news);
            service.Insert(news);
            service.Save();

            // Act
            var valid = validator.IsValid();

            validator.AddToModelError(controller);
            var result     = controller.Create(newsViewModel) as RedirectToRouteResult;
            var actionName = result.RouteValues.Values.ElementAt(0);

            // Assert
            Assert.That(result, !Is.Null);
            Assert.That("Index", Is.EqualTo(actionName));
            Assert.That(valid, Is.True);
        }
Beispiel #5
0
        public void Good_Post_Create()
        {
            // Arrange
            var menuItemViewModel = new MenuItemViewModel()
            {
                Position       = 1,
                Title          = "Strona glowna",
                ActionName     = "Index",
                ControllerName = "Home"
            };
            var menuItem = new MenuItem()
            {
                Position       = 1,
                Title          = "Strona glowna",
                ActionName     = "Index",
                ControllerName = "Home"
            };
            var validator  = new ModelValidator <MenuItemViewModel>(menuItemViewModel);
            var service    = Substitute.For <IMenuItemRepository>();
            var mapper     = Substitute.For <IMapper>();
            var controller = new MenuItemController(service, mapper);

            mapper.Map <MenuItemViewModel, MenuItem>(menuItemViewModel).Returns(menuItem);
            service.Insert(menuItem);
            service.Save();

            // Act
            var valid = validator.IsValid();

            validator.AddToModelError(controller);
            var result     = controller.Create(menuItemViewModel) as RedirectToRouteResult;
            var actionName = result.RouteValues.Values.ElementAt(0);

            // Assert
            Assert.That(result, !Is.Null);
            Assert.That("Index", Is.EqualTo(actionName));
            Assert.That(valid, Is.True);
        }
        public void Good_Post_Edit()
        {
            // Arrange
            var drink = new Drink()
            {
                ID       = 1,
                Name     = "Mirinda",
                Price    = 5.00M,
                Capacity = 0.5f
            };
            var drinkViewModel = new DrinkViewModel()
            {
                ID       = 1,
                Name     = "Mirinda",
                Price    = 5.00M,
                Capacity = 0.5f
            };
            var repository = Substitute.For <IDrinkRepository>();
            var mapper     = Substitute.For <IMapper>();
            var controller = new DrinkController(repository, mapper);
            var validator  = new ModelValidator <DrinkViewModel>(drinkViewModel);

            repository.Get(drinkViewModel.ID).Returns(drink);
            mapper.Map <DrinkViewModel, Drink>(drinkViewModel).Returns(drink);
            repository.Update(drink);
            repository.Save();

            // Act
            var result     = controller.Edit(drinkViewModel) as RedirectToRouteResult;
            var actionName = result.RouteValues.Values.ElementAt(0);
            var valid      = validator.IsValid();

            // Assert
            Assert.That(result, !Is.Null);
            Assert.That("Index", Is.EqualTo(actionName));
            Assert.That(valid, Is.True);
        }
        public async Task <UserBlackListDTO> EditBlackList(UserBLEditDTO userBLEditDTO, int userId)
        {
            ValidationResults result = ModelValidator.IsValid(userBLEditDTO);

            if (!result.Successed)
            {
                throw ValidationExceptionBuilder.BuildValidationException(result);
            }

            HotelAdmin hotelAdmin = context.HotelAdmins.Get(userId);

            if (hotelAdmin == null)
            {
                throw new NotFoundException("No such hotel");
            }

            Guest guest = context.Guests.Get(userBLEditDTO.GuestId);

            if (guest == null)
            {
                throw new NotFoundException("No such user");
            }
            int hotelId       = hotelAdmin.Hotel.Id;
            var userBlackList = context.UserBlackLists.GetAll()
                                .Where(x => x.HotelId == hotelId &&
                                       x.GuestId == userBLEditDTO.GuestId).FirstOrDefault();

            if (userBlackList == null)
            {
                throw new NotFoundException("No such user in the hotel's black list");
            }
            userBlackList.Reason = userBLEditDTO.Reason;
            context.UserBlackLists.Update(userBlackList);
            await context.SaveAsync();

            return(userBlackList.ToUserBlackListDTO());
        }
Beispiel #8
0
        public void Post_Edit_Is_Not_Valid()
        {
            // Arrange
            var pizzaViewModel = new PizzaViewModel()
            {
                ID            = 1,
                Name          = "Margarita",
                PriceForLarge = 30.00M,
                //PriceForMedium = 20.00M,
                PriceForSmall = 15.00M,
                Components    = new List <int>()
                {
                    1
                }
            };
            var service    = Substitute.For <IPizzaService>();
            var controller = new PizzaController(service);
            var validator  = new ModelValidator <PizzaViewModel>(pizzaViewModel);

            service.UpdatePizza(pizzaViewModel);
            service.SavePizza();

            // Act
            var valid = validator.IsValid();

            validator.AddToModelError(controller);
            var result     = controller.Edit(pizzaViewModel) as RedirectToRouteResult;
            var actionName = result.RouteValues.Values.ElementAt(0);
            var tempData   = controller.TempData["ModelIsNotValid"];

            // Assert
            Assert.That(result, !Is.Null);
            Assert.That(valid, Is.False);
            Assert.That("Wystąpił błąd w formularzu, spróbuj ponownie.", Is.EqualTo(tempData));
            Assert.That("Index", Is.EqualTo(actionName));
        }
        public void Post_Create_Model_Not_Valid()
        {
            // Arrange
            var informationItemViewModel = new InformationItemViewModel()
            {
                //Position = 1,
                //Title = "Menu",
                Content = "Ut at viverra arcu. Donec sed interdum nulla, eu porttitor lorem. Morbi efficitur sapien ullamcorper lorem vestibulum, ut aliquet turpis consequat. Suspendisse ac nibh non velit scelerisque bibendum. "
            };
            var fileName    = "text.jpg";
            var fileLength  = 1000;
            var contentType = "image";
            var fakeImage   = Substitute.For <HttpPostedFileBase>();
            var validator   = new ModelValidator <InformationItemViewModel>(informationItemViewModel);
            var service     = Substitute.For <IInformationItemService>();

            fakeImage.FileName.Returns(fileName);
            fakeImage.ContentType.Returns(contentType);
            fakeImage.ContentLength.Returns(fileLength);

            var controller = new InformationItemController(service);

            // Act
            var valid = validator.IsValid();

            validator.AddToModelError(controller);
            var result     = controller.Create(informationItemViewModel, fakeImage) as RedirectToRouteResult;
            var actionName = result.RouteValues.Values.ElementAt(0);
            var tempData   = controller.TempData["ModelIsNotValid"];

            // Assert
            Assert.That(valid, Is.False);
            Assert.That(result, !Is.Null);
            Assert.That("Wystąpił błąd w formularzu, spróbuj ponownie.", Is.EqualTo(tempData));
            Assert.That("Index", Is.EqualTo(actionName));
        }
        public void Post_Create_Model_Not_Valid()
        {
            // Arrange
            var sliderItemViewModel = new SliderItemViewModel()
            {
                //Position = 1,
                ShortDescription = "Slider description 1",
                PictureUrl       = "/Content/Images/pizzaSlide_1.jpg"
            };
            var fileName    = "text.jpg";
            var fileLength  = 1000;
            var contentType = "image";
            var fakeImage   = Substitute.For <HttpPostedFileBase>();
            var validator   = new ModelValidator <SliderItemViewModel>(sliderItemViewModel);
            var service     = Substitute.For <ISliderItemService>();

            fakeImage.FileName.Returns(fileName);
            fakeImage.ContentType.Returns(contentType);
            fakeImage.ContentLength.Returns(fileLength);

            var controller = new SliderItemController(service);

            // Act
            var valid = validator.IsValid();

            validator.AddToModelError(controller);
            var result     = controller.Create(sliderItemViewModel, fakeImage) as RedirectToRouteResult;
            var actionName = result.RouteValues.Values.ElementAt(0);
            var tempData   = controller.TempData["ModelIsNotValid"];

            // Assert
            Assert.That(valid, Is.False);
            Assert.That(result, !Is.Null);
            Assert.That("Wystąpił błąd w formularzu, spróbuj ponownie.", Is.EqualTo(tempData));
            Assert.That("Index", Is.EqualTo(actionName));
        }
Beispiel #11
0
        /// <summary>
        /// Update base user profile
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public virtual async Task <ResultModel> UpdateBaseUserProfileAsync(UserProfileEditViewModel model)
        {
            var modelState = ModelValidator.IsValid(model);

            if (!modelState.IsSuccess)
            {
                return(modelState);
            }

            var resultModel        = new ResultModel();
            var currentUserRequest = await _userManager.GetCurrentUserAsync();

            if (!currentUserRequest.IsSuccess)
            {
                resultModel.Errors.Add(new ErrorModel(string.Empty, "User not found!"));
                return(resultModel);
            }

            var currentUser = currentUserRequest.Result;

            var isUsed = await _userManager.UserManager
                         .Users.AnyAsync(x => !x.Id.Equals(currentUser.Id) &&
                                         !x.Email.IsNullOrEmpty() &&
                                         x.Email.ToLowerInvariant()
                                         .Equals(model.Email.ToLowerInvariant()));

            if (isUsed)
            {
                resultModel.AddError("Email is used by another user");
                return(resultModel);
            }

            currentUser.FirstName      = model.FirstName;
            currentUser.LastName       = model.LastName;
            currentUser.Birthday       = model.Birthday;
            currentUser.AboutMe        = model.AboutMe;
            currentUser.PhoneNumber    = model.PhoneNumber;
            currentUser.EmailConfirmed = currentUser.EmailConfirmed && model.Email.Equals(currentUser.Email);
            currentUser.Email          = model.Email;

            if (!currentUser.EmailConfirmed)
            {
                EmailEvents.Events.TriggerSendConfirmEmail(new SendConfirmEmailEventArgs
                {
                    HttpContext = _accessor.HttpContext,
                    Email       = model.Email
                });
            }

            var result = await _userManager.UserManager.UpdateAsync(currentUser);

            if (result.Succeeded)
            {
                resultModel.IsSuccess = true;
                return(resultModel);
            }

            resultModel.AppendIdentityErrors(result.Errors);

            return(resultModel);
        }
 public void Test_TrasferReq_ValidModel()
 {
     Assert.True(ModelValidator.IsValid(BASE_MODEL));
 }