예제 #1
0
        public async Task RegisterUser_AddNewUser_CreateCustomer_ShouldCreateCustomer(AutoMoqDataValidFixtures fixtures, IdentityUser identityUser)
        {
            //Arrange
            identityUser.Id = Guid.NewGuid().ToString();
            var expectedResult = new ValidationResult();


            var responseMessage = new ResponseMessage(expectedResult);

            _messageBusMock.Setup(s => s.RequestAsync <UserSaveIntegrationEvent, ResponseMessage>(It.IsAny <UserSaveIntegrationEvent>())).ReturnsAsync(responseMessage);

            _userRegisterProviderMock.Setup(s => s.CreateUserAsync(It.IsAny <IdentityUser>(), It.IsAny <string>())).ReturnsAsync(IdentityResult.Success).Verifiable();
            _userRegisterProviderMock.Setup(s => s.FindByEmailAsync(It.IsAny <string>())).ReturnsAsync(identityUser);



            var command = new CreateNewUserCommand("123", "Alexandre", "*****@*****.**", "*****@*****.**", "A3£fksk@sf324");

            _sut = new UserRegisterCommandHandler(_userRegisterProviderMock.Object, _mediatorHandlerMock.Object, _messageBusMock.Object);

            //Act
            var response = await _sut.Handle(command, CancellationToken.None);

            //Assert
            response.ValidationResult.IsValid.Should().Be(true);
        }
예제 #2
0
        public async Task <CommandResult <ValidationResult> > Handle(CreateNewUserCommand message, CancellationToken cancellationToken)
        {
            if (!message.IsValid())
            {
                return(new CommandResult <ValidationResult>(message.ValidationResult));
            }

            var user = new IdentityUser
            {
                UserName       = message.Email,
                Email          = message.Email,
                EmailConfirmed = false // Will send email to confirm the account
            };

            var userCreated = await _userRegisterProvider.CreateUserAsync(user, message.Password).ConfigureAwait(false);

            if (userCreated.Succeeded)
            {
                var result = await CreateCustomer(message);

                return(new CommandResult <ValidationResult>(result.ValidResult));
            }

            return(new CommandResult <ValidationResult>(new ValidationResult(userCreated.Errors.Select(e => new ValidationFailure(e.Code, e.Description)))));
        }
        public async Task Should_create_test_api_user()
        {
            const string EMAIL_STEM = EmailData.FAKE_EMAIL_STEM;
            const int    NUMBER     = 1;

            var request = new UserBuilder(EMAIL_STEM, NUMBER)
                          .WithUserType(UserType.Judge)
                          .ForApplication(Application.TestApi)
                          .BuildRequest();

            var command = new CreateNewUserCommand
                          (
                request.Username, request.ContactEmail, request.FirstName, request.LastName, request.DisplayName,
                request.Number, request.TestType, request.UserType, request.Application, request.IsProdUser
                          );

            await _commandHandler.Handle(command);

            var userId = command.NewUserId;

            var user = await Context.Data.GetUserById(userId);

            user.Application.Should().Be(request.Application);
            user.ContactEmail.Should().Be(request.ContactEmail);
            user.CreatedDate.Should().BeCloseTo(DateTime.UtcNow, TimeSpan.FromSeconds(5));
            user.DisplayName.Should().Be(request.DisplayName);
            user.FirstName.Should().Be(request.FirstName);
            user.LastName.Should().Be(request.LastName);
            user.Number.Should().Be(NUMBER);
            user.Username.Should().Be(request.Username);
            user.UserType.Should().Be(request.UserType);
        }
예제 #4
0
        public async Task RegisterUser_AddNewUser_CreateCustomer_ShouldFail(AutoMoqDataValidFixtures fixtures, IdentityUser identityUser)
        {
            //Arrange
            var expectedResult = new ValidationResult();

            expectedResult.Errors.Add(CreateValidationFailure("0", "Error to create a new customer, same identity Number defined"));

            identityUser.Id = Guid.NewGuid().ToString();

            var responseMessage = new ResponseMessage(expectedResult);

            _messageBusMock.Setup(s => s.RequestAsync <UserSaveIntegrationEvent, ResponseMessage>(It.IsAny <UserSaveIntegrationEvent>())).ReturnsAsync(responseMessage);

            _userRegisterProviderMock.Setup(s => s.CreateUserAsync(It.IsAny <IdentityUser>(), It.IsAny <string>())).ReturnsAsync(IdentityResult.Success).Verifiable();
            _userRegisterProviderMock.Setup(s => s.FindByEmailAsync(It.IsAny <string>())).ReturnsAsync(identityUser);

            _mediatorHandlerMock.Setup(s => s.PublishEvent(It.IsAny <UserCanceledEvent>()))
            .Verifiable("Notification was not sent");

            var command = new CreateNewUserCommand("123", "Alexandre", "*****@*****.**", "*****@*****.**", "A3£fksk@sf324");

            _sut = new UserRegisterCommandHandler(_userRegisterProviderMock.Object, _mediatorHandlerMock.Object, _messageBusMock.Object);

            //Act
            var response = await _sut.Handle(command, CancellationToken.None);

            //Assert
            _mediatorHandlerMock.Verify(m => m.PublishEvent(It.IsAny <UserCanceledEvent>()), Times.Once());
            response.ValidationResult.Errors.Should().HaveCount(1);
            response.ValidationResult.Errors.Select(s => s.ErrorMessage).Should().Contain(expectedResult.Errors.FirstOrDefault().ErrorMessage);
        }
예제 #5
0
        private async Task <ResponseMessage> CreateCustomer(CreateNewUserCommand message)
        {
            var user = await _userRegisterProvider.FindByEmailAsync(message.Email).ConfigureAwait(false);

            var userSaved = new UserSaveIntegrationEvent(Guid.Parse(user.Id), message.Name, user.Email, message.IdentityNumber);

            try
            {
                var result = await _messageBus.RequestAsync <UserSaveIntegrationEvent, ResponseMessage>(userSaved).ConfigureAwait(false);

                if (!result.IsValid())
                {
                    var @event = new UserCanceledEvent(Guid.Parse(user.Id), message.IdentityNumber, message.Name, message.Email);
                    @event.ValidationResult = result.ValidResult;
                    await _mediator.PublishEvent(@event);

                    return(result);
                }
                await _mediator.PublishEvent(new CustomerCreatedEvent(result.AggregateId, message.Name, message.Email)).ConfigureAwait(false);

                return(result);
            }
            catch (Exception ex)
            {
                var @event = new UserCanceledEvent(Guid.Parse(user.Id), message.IdentityNumber, message.Name, message.Email);
                @event.ValidationResult.Errors.Add(new FluentValidation.Results.ValidationFailure(string.Empty, ex.Message));
                await _mediator.PublishEvent(@event).ConfigureAwait(false);

                return(new ResponseMessage(@event.ValidationResult));
            }
        }
예제 #6
0
        public async Task <Guid> HandleCommand(CreateNewUserCommand cmd)
        {
            var org = _organizationRepository.Get(cmd.OrganizationId);

            if (org == null)
            {
                throw new Exception("Organization does not exist.");
            }

            var user = org.AddNewUser(cmd.FirstName, cmd.LastName, cmd.Email, cmd.PhoneNumber, cmd.IdentityId, active: true);

            _organizationRepository.Save();

            await _messageProducer.ProduceEventAsync <UserCreatedEvent>(new UserCreatedEvent {
                CorrelationId  = (cmd.CommandId == null) ? Guid.NewGuid() : (Guid)cmd.CommandId,
                Active         = user.Active,
                DateJoined     = user.DateJoined,
                Email          = user.Email,
                EntityId       = user.ID,
                FirstName      = user.FirstName,
                LastName       = user.LastName,
                IdentityId     = user.IdentityId,
                OrganizationId = org.ID,
                PhoneNumber    = user.PhoneNumber,
                TimeStamp      = DateTime.UtcNow
            });

            return(user.ID);
        }
예제 #7
0
        public HomeViewModel()
        {
            CreateNewUserCommand          = new CreateNewUserCommand(this);
            ChangeUserInformationsCommand = new ChangeUserInforamtionsCommand(this);
            NewPravniAktCommand           = new NewPravniAktCommand(this);
            DeleteAktCommand = new DeleteAktCommand(this);

            PravneAkte = new BindingList <Common.Models.PravniAkt>();


            PravniAktToDelete = new Zakon();

            Task t1 = new Task(() =>
            {
                while (true)
                {
                    Thread.Sleep(1000);
                    //Letovi = new BindingList<LetPrikaz>(Channel.Instance.flyghtsProxy.GetFlyghts().ToList());
                    //Gradovi = new BindingList<Grad>(Channel.Instance.citiesProxy.GetCities().ToList());
                    //Avioni = new BindingList<Avion>(Channel.Instance.airplaneProxy.GetAirplanes().ToList());

                    PravneAkte = new BindingList <Common.Models.PravniAkt>(Channel.Instance.pravniAktProxy.PravneAkte().ToList());
                }
            });

            t1.Start();
        }
예제 #8
0
        public async Task <IActionResult> Register(UserRegisterView userRegister)
        {
            var command = new CreateNewUserCommand(userRegister.IdentityNumber, userRegister.Name, userRegister.Email, userRegister.Email, userRegister.Password);

            var result = await _mediator.SendCommand <CreateNewUserCommand, ValidationResult>(command).ConfigureAwait(false);

            return(CustomResponse <ValidationResult>(result));
        }
예제 #9
0
        public async Task <IActionResult> Post([FromServices] IMediatorHandler bus, [FromBody] AdicionarUsuarioModel novoUsuarioModel)
        {
            var comando = new CreateNewUserCommand(novoUsuarioModel.Nome, novoUsuarioModel.Login, novoUsuarioModel.Email,
                                                   novoUsuarioModel.Senha, novoUsuarioModel.ConfirmaSenha, novoUsuarioModel.Grupos);
            await bus.SendCommand(comando);

            return(ResponseCreated($"api/usuarios/{comando.Id}", new UsuarioAdicionadoModel {
                Id = comando.Id, Login = comando.UserName
            }));
        }
        public async Task Should_not_create_test_api_user_if_matching_number_exists()
        {
            const string EMAIL_STEM = EmailData.FAKE_EMAIL_STEM;

            var firstUser = await Context.Data.SeedUser();

            var request = new UserBuilder(EMAIL_STEM, firstUser.Number)
                          .WithUserType(firstUser.UserType)
                          .ForApplication(firstUser.Application)
                          .BuildRequest();

            var command = new CreateNewUserCommand
                          (
                request.Username, request.ContactEmail, request.FirstName, request.LastName, request.DisplayName,
                request.Number, request.TestType, request.UserType, request.Application, request.IsProdUser
                          );

            Assert.ThrowsAsync <MatchingUserWithNumberExistsException>(() => _commandHandler.Handle(command));
        }
        public async Task <IActionResult> CreateUser([FromBody] CreateNewUserCommand cmd)
        {
            try
            {
                var userId = await _createNewUserCommandHandler.HandleCommand(cmd);

                return(Ok(new NewUserResultDto {
                    Id = userId
                }));
            }
            catch (Exception ex)
            {
                if (ex is FormatException)
                {
                    return(BadRequest(ex.Message));
                }
                //TODO: log what happened here...
                return(BadRequest("There was an error"));
            }
        }
        public async Task Test_EventSourcing()
        {
            var command = new CreateNewUserCommand(Guid.Empty, "Higor César", "*****@*****.**",
                                                   new DateTime(1985, 01, 22), "higorcesar");

            var bus = _serviceProvider.GetService <IMediatorHandler>();

            await bus.SendCommand(command);

            var repository = _serviceProvider.GetService <IEventStoreRepository>();

            var result = await repository.All(command.Id);

            Debug.Assert(result != null, $"{nameof(result)} != null");
            var obj = JsonConvert.DeserializeObject <CreateNewUserCommand>(result.FirstOrDefault().Data);

            Assert.Equal(command.Id, obj.AggregateId);
            Assert.Equal(command.Name, obj.Name);
            Assert.Equal(command.Email, obj.Email);
            Assert.Equal(command.Birthday, obj.Birthday);
        }
예제 #13
0
        public async Task RegisterUser_AddNewUser_UserAlreadyExists(AutoMoqDataValidFixtures fixtures)
        {
            //Arrange
            var identityError = new IdentityError
            {
                Code        = "1",
                Description = "Username already exists"
            };

            _userRegisterProviderMock.Setup(s => s.CreateUserAsync(It.IsAny <IdentityUser>(), It.IsAny <string>())).ReturnsAsync(IdentityResult.Failed(identityError)).Verifiable();

            var command = new CreateNewUserCommand("123", "Alexandre", "*****@*****.**", "*****@*****.**", "A3£fksk@sf324");

            _sut = new UserRegisterCommandHandler(_userRegisterProviderMock.Object, _mediatorHandlerMock.Object, _messageBusMock.Object);

            //Act
            var response = await _sut.Handle(command, CancellationToken.None);

            //Assert
            response.ValidationResult.Errors.Should().HaveCount(1);
            response.ValidationResult.Errors.Select(s => s.ErrorMessage).Should().Contain(identityError.Description);
        }
예제 #14
0
        public async Task RegisterUser_AddNewUser_InvalidCommand(AutoMoqDataValidFixtures fixtures)
        {
            //Arrange
            var expectedResult = new ValidationResult();

            expectedResult.Errors.Add(CreateValidationFailure("-1000", "Identity Number is required"));
            expectedResult.Errors.Add(CreateValidationFailure("-1001", "Name is required"));
            expectedResult.Errors.Add(CreateValidationFailure("-1002", "Username is required"));
            expectedResult.Errors.Add(CreateValidationFailure("-1005", "Invalid format of the email"));
            expectedResult.Errors.Add(CreateValidationFailure("-1003", "Email is required"));
            expectedResult.Errors.Add(CreateValidationFailure("-1004", "Password is required"));

            var command = new CreateNewUserCommand(string.Empty, string.Empty, string.Empty, string.Empty, string.Empty);

            _sut = new UserRegisterCommandHandler(_userRegisterProviderMock.Object, _mediatorHandlerMock.Object, _messageBusMock.Object);

            //Act
            var response = await _sut.Handle(command, CancellationToken.None);

            //Assert
            response.ValidationResult.Errors.Should().HaveCount(7);
            response.ValidationResult.Errors.Select(s => s.ErrorCode).Should().Contain(expectedResult.Errors.Select(s => s.ErrorCode));
            response.ValidationResult.Errors.Select(s => s.ErrorMessage).Should().Contain(expectedResult.Errors.Select(s => s.ErrorMessage));
        }
        public async Task <ActionResult <User> > PostUser([FromBody] CreateNewUserCommand userEntity)
        {
            var result = await _mediator.Send(userEntity);

            return(CreatedAtAction("GetUser", new { id = result.ID }, result));
        }
 public async Task <IActionResult> Post([FromBody] CreateNewUserCommand command) =>
 Ok(await _mediator.Send(command));
예제 #17
0
        public async Task <ActionResult <CommandResult> > Register([FromBody] CreateNewUserCommand command)
        {
            var resp = await _userHandler.Handler(command);

            return(resp.Success ? StatusCode(201, resp) : BadRequest(resp));
        }
        public async Task <IActionResult> CreateUserByFranchisee([FromForm] CreateNewUserCommand command)
        {
            var result = await _mediator.Send(command);

            return(result);
        }
예제 #19
0
        public async Task <IActionResult> CreateUser([FromBody] CreateNewUserCommand data)
        {
            var res = await Mediator.Send(data);

            return(Ok(res));
        }