Пример #1
0
 public Task <UserDetailsResponse> CreateAsync(UserCreateCommand command,
                                               CancellationToken cancellationToken = default)
 {
     return(flurlClient.Request(basePath)
            .PostJsonAsync(command, cancellationToken)
            .ReceiveJson <UserDetailsResponse>());
 }
Пример #2
0
        public async Task <UserModel> CreateAsync(UserCreateCommand cmd)
        {
            var result = await ExecuteAsync <UserCreateCommand, UserCreateCommandValidator, UserModel>(cmd, async() =>
            {
                // check to see if the user already exists by username
                var existingUser = Get <User>(u => u.Username.ToLower().Equals(cmd.Username.ToLower()));

                // if the user exists throw an exception b/c the usernames have to be unique
                if (null != existingUser)
                {
                    throw new UserExistsException($"A user with username {cmd.Username} already exists.");
                }

                // create the user
                var user = new User(firstName: cmd.FirstName,
                                    email: cmd.Email,
                                    username: cmd.Username,
                                    hashedPassword: _passwordService.CreatePasswordHash(cmd.Password),
                                    createdByUserId: MessageContext.UserId);

                // save the user
                await Database.SaveAsync(user).ConfigureAwait(false);

                // convert the user to it's model
                var model = UserFactory.ConvertToModel(user);

                // publish the domain event
                Publish(new UserCreatedEvent(model, MessageContext));

                // return the user model
                return(model);
            }).ConfigureAwait(false);

            return(result);
        }
        public ActionResult Create(UserCreateCommand userCreateCommand, User currentUser, ProposedUser proposedUser)
        {
            Require.NotNull(userCreateCommand, "userCreateCommand");

            if (ModelState.IsValid)
            {
                IdentityResult identityResult = UserManager.PasswordValidator.ValidateAsync(userCreateCommand.Password).Result;

                if (identityResult.Succeeded)
                {
                    string passwordHash = UserManager.PasswordHasher.HashPassword(userCreateCommand.Password);

                    UserService.Create(passwordHash,
                                       userCreateCommand.UserContactDto,
                                       userCreateCommand.UserDataDto,
                                       userCreateCommand.UserPaymentDto,
                                       userCreateCommand.UserPermissionDto,
                                       new EntityCreatedDto(currentUser, DateTime.Now));
                    if (proposedUser != null)
                    {
                        ProposedUserService.Delete(proposedUser);
                    }

                    return(RedirectToAction("Index", "UserAdministration"));
                }
                AddErrors(identityResult);
            }
            UserCreateViewModel userCreateViewModel = new UserCreateViewModel(Roles.AllRoles,
                                                                              userCreateCommand,
                                                                              UserGroupService.GetAll(),
                                                                              proposedUser);

            return(View(userCreateViewModel));
        }
Пример #4
0
        public async Task <IActionResult> Create(UserAddInfo user)
        {
            try
            {
                UserCreateCommand userCreate = new UserCreateCommand()
                {
                    Email         = user.Email,
                    FirstName     = user.FirstName,
                    LastName      = user.LastName,
                    Password      = user.Password,
                    Phone         = user.Phone,
                    UserName      = user.UserName,
                    SocialAddress = new Domain.SocialMedia(instageram: user.Instageram, telegramCanal: user.TelegramCanal, telegramGroup: user.TelegramGroup),
                    Address       = new Domain.Address(street: user.Street, city: user.City, state: user.State, country: user.Country, zipcode: user.ZipCode)
                };

                var result = await _mediator.Send(userCreate);

                return(Ok(result));
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #5
0
        public async Task <ResponseViewModel> CreateAsync(UserCreateRequestViewModel request)
        {
            using (_unitOfWork)
            {
                // Inicia a transação
                _unitOfWork.BeginTransaction();

                // Adiciona o Perfil
                ProfileCreateCommand profileCreateCommand  = new ProfileCreateCommand(Convert.ToInt32(request.IdType), Guid.NewGuid().ToString(), request.Avatar, request.CpfCnpj, request.Address);
                ResponseCommand      profileCreateResponse = await _mediator.Send(profileCreateCommand, CancellationToken.None).ConfigureAwait(true);

                if (!profileCreateResponse.Success)
                {
                    return(new ResponseViewModel(false, profileCreateResponse.Object));
                }

                // Adiciona o Usuário
                UserCreateCommand userCreateCommand  = new UserCreateCommand((int)profileCreateResponse.Object, Guid.NewGuid().ToString(), request.Name, request.Email);
                ResponseCommand   userCreateResponse = await _mediator.Send(userCreateCommand, CancellationToken.None).ConfigureAwait(true);

                if (!userCreateResponse.Success)
                {
                    return(new ResponseViewModel(false, userCreateResponse.Object));
                }

                // Comita e Retorna
                _unitOfWork.CommitTransaction();
                return(new ResponseViewModel(true, "User created"));
            }
        }
        public void UserCreateCommand()
        {
            //var client = new JsonServiceClient();

            var command = new UserCreateCommand
            {
                FirstName = "Test",
                LastName = "User",
                Email = "*****@*****.**",
                DisplayName = "Sir. Test User",
                Password = "******"
            };

            var service = testSetup.Resolve<ISimpleBudgetService>();

            var response = service.Post(command) as CreateResponse;

            using (var context = testSetup.Resolve<IRepositoryUnitOfWork>())
            {
                var user = context.Users.Get(response.Id);

                Assert.IsNotNull(user);
                Assert.AreEqual(command.FirstName, user.FirstName);
                Assert.AreEqual(command.LastName, user.LastName);
                Assert.AreEqual(command.Email, user.Email);
                Assert.AreEqual(command.DisplayName, user.DisplayName);
                Assert.AreEqual(Common.HashPassword(command.Password), user.PasswordHash);
            }
        }
Пример #7
0
        public async Task <IActionResult> CreateUser([FromBody] UserCreateCommand cmd)
        {
            var result = await _mediator.Send(cmd);

            // var result = await _userService.CreateUser(data);
            return(result != 0 ? Ok(new { data = result, is_successd = true }) : Ok(new { is_successd = false }));
        }
Пример #8
0
        public async Task <IActionResult> Post()
        {
            var userCreateCommand = new UserCreateCommand("", "");

            var createdUserId = await _commandDispather.Execute(userCreateCommand);

            return(Ok(createdUserId));
        }
Пример #9
0
        public void Should_Show_Error_When_IdProfile_Invalid(int idProfile)
        {
            UserCreateCommand userCreateCommand = new UserCreateCommand(idProfile, Guid.NewGuid().ToString(), _faker.Person.FullName, _faker.Person.Email);

            userCreateCommand.Validate();

            Assert.True(!userCreateCommand.IsValid());
            Assert.True(userCreateCommand.Errors?.FirstOrDefault(x => x == "Profile is required") != null);
        }
Пример #10
0
        public void Should_Show_Error_When_Email_Null_Or_Empty(string email)
        {
            UserCreateCommand userCreateCommand = new UserCreateCommand(1, Guid.NewGuid().ToString(), _faker.Person.FullName, email);

            userCreateCommand.Validate();

            Assert.True(!userCreateCommand.IsValid());
            Assert.True(userCreateCommand.Errors?.FirstOrDefault(x => x == "E-mail is required") != null);
        }
Пример #11
0
 public async Task <IActionResult> Create([FromRoute] Guid companyId, [FromBody] UserCreateCommand command)
 => HandleCommand(await _mediator.Send(new UserCreate.Command(
                                           userId: UserId,
                                           userCompany: CompanyId,
                                           companyId,
                                           command.Email, command.Cpf,
                                           command.FirstName, command.LastName,
                                           command.Language, command.Login, command.Password,
                                           Role
                                           )));
        public int Create(UserCreateCommand request)
        {
            const string sql = "" +
                               " INSERT INTO " +
                               " FgjCqrsUser (Guid, IdProfile, Name, Email) " +
                               "      VALUES (@Guid, @IdProfile, @Name, @Email) " +
                               " SELECT @@IDENTITY";

            return(_unitOfWork.Connection.ExecuteScalar <int>(sql, request, _unitOfWork?.Transaction));
        }
Пример #13
0
        public async Task <IActionResult> Create(UserCreateCommand command)
        {
            IdentityResult result = await mediator.Send(command);

            if (!result.Succeeded)
            {
                return(BadRequest(result.Errors));
            }

            return(Ok());
        }
Пример #14
0
        public async Task <IActionResult> CreateUser(UserCreateCommand model)
        {
            var command = await _mediator.Send(model);

            if (command.IsSuccess)
            {
                return(Ok(command.Result));
            }

            return(BadRequest(command.ErrorMessage));
        }
Пример #15
0
        public async Task <ActionResult> Post(UserCreateCommand command)
        {
            var result = await _appService.PostAsync(command);

            if (_notificationProvider.HasErrors())
            {
                return(BadRequest(new FailedResult("Bad Request", _notificationProvider.GetErrors())));
            }

            return(Ok(result));
        }
Пример #16
0
 public async Task <ActionResult <User> > CreateUser([FromBody] UserCreateCommand user)
 {
     try
     {
         return(await _mediator.Send(mapper.Map <UserCreateCommand>(user)));
     }
     catch (Exception ex)
     {
         throw;
     }
 }
Пример #17
0
        public async Task Should_Show_Error_When_Duplicate_Name()
        {
            UserCreateCommand userCreateCommand = new UserCreateCommand(1, Guid.NewGuid().ToString(), _faker.Person.FullName, _faker.Person.Email);

            _userValidationMock.Setup(r => r.IsDuplicateName(It.IsAny <string>(), It.IsAny <string>())).Returns(Tuple.Create(true, "Name already exist"));

            ResponseCommand response = await _userCreateCommandHandler.Handle(userCreateCommand, CancellationToken.None).ConfigureAwait(true);

            Assert.True(!response.Success);
            Assert.True(((List <string>)response.Object).Count > 0);
            Assert.True(((List <string>)response.Object).Find(x => x == "Name already exist") != null);
        }
Пример #18
0
        public async Task Should_Create_User_When_All_Parameters_Success()
        {
            UserCreateCommand userCreateCommand = new UserCreateCommand(1, Guid.NewGuid().ToString(), _faker.Person.FullName, _faker.Person.Email);

            _userValidationMock.Setup(r => r.IsDuplicateName(It.IsAny <string>(), It.IsAny <string>())).Returns(Tuple.Create(false, "Name already exist"));
            _userSqlServerRepositoryMock.Setup(r => r.Create(It.IsAny <UserCreateCommand>())).Returns(_faker.Random.Number(1, 100));

            ResponseCommand response = await _userCreateCommandHandler.Handle(userCreateCommand, CancellationToken.None).ConfigureAwait(true);

            Assert.True(response.Success);
            Assert.True((int)response.Object > 0);
        }
Пример #19
0
        public async Task Should_Show_Error_When_Some_Parameters_Is_Invalid()
        {
            UserCreateCommand userCreateCommand = new UserCreateCommand(1, Guid.NewGuid().ToString(), _faker.Person.FullName, _faker.Person.Email);

            userCreateCommand.AddError("Meu erro para testar o UnitTest");

            ResponseCommand response = await _userCreateCommandHandler.Handle(userCreateCommand, CancellationToken.None).ConfigureAwait(true);

            Assert.True(!response.Success);
            Assert.True(((List <string>)response.Object).Count > 0);
            Assert.True(((List <string>)response.Object).Find(x => x == "Meu erro para testar o UnitTest") != null);
        }
Пример #20
0
        public async Task <IActionResult> Create(UserCreateCommand user)
        {
            try
            {
                var result = await _mediator.Send(user);

                return(Ok(result));
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #21
0
        public async Task <ObjectResult> PostAsync(UserCreateCommand command)
        {
            ValidationResult resultadoValidacao = command.Validate();

            if (!resultadoValidacao.IsValid)
            {
                throw new Exception("Erro de validação!");
            }

            await _userService.AddAsync(command);

            return(StatusCode(201, command));
        }
Пример #22
0
        public async Task <int> CreateAsync(UserCreateCommand command)
        {
            var userCountByUsername = await _repository.CountAsync(x => x.Username.Equals(command.Username));

            Guard.Against(userCountByUsername > 0, ErrorType.Duplicating);

            var user = _mapper.Map <User>(command);

            user.Role = Role.Client;

            var createdUser = await _repository.CreateAsync(user);

            return(await CommitAsync() > 0 ? createdUser.ID : 0);
        }
Пример #23
0
        public async Task <OperationResult <IdentityResult> > Handle(UserCreateCommand request, CancellationToken cancellationToken)
        {
            var user = new User {
                UserName = request.UserName
            };
            var result = await _userManager.CreateAsync(user, request.Password);

            if (result.Succeeded)
            {
                return(OperationResult <IdentityResult> .BuildSuccessResult(result));
            }

            return(OperationResult <IdentityResult> .BuildFailure("", result));
        }
Пример #24
0
        public async Task Call_To_Create_Endpoint_And_Return_Ok()
        {
            var data = new UserCreateCommand()
            {
                Name    = "RandomName1",
                Surname = " RandomSurname1",
            };
            var response = await this.PostAsync <UserIdResponse, UserCreateCommand>(
                data : data,
                expectedStatusCode : HttpStatusCode.OK,
                successStatusCode : true);

            this._idToRemove = response.Id;
        }
        public async Task<IActionResult> Create(UserCreateCommand command) 
        {
            if (ModelState.IsValid) 
            {
                var result = await _mediator.Send(command);

                if (!result.Succeeded) 
                {
                    return BadRequest(result.Errors);
                }

                return Ok();
            }

            return BadRequest();
        }
Пример #26
0
        public async Task <int> AddAsync(UserCreateCommand command)
        {
            var isUnique = await _userRepository.IsUniqueAsync(command.Email);

            if (isUnique)
            {
                throw new Exception("Não foi possível cadastrar o usuário, pois já existe um usuário cadastrado com esse email!");
            }

            var user = Mapper.Map <User>(command);

            user.SetPassword(command.Password, _encrypter);
            var addResult = await _userRepository.AddAsync(user);

            return(addResult.Id);
        }
Пример #27
0
        public async Task <IActionResult> Create(UserCreateCommand command)
        {
            if (ModelState.IsValid)
            {
                var result = await _mediator.Send(command);

                if (result.Succeeded)
                {
                    return(BadRequest(result.Errors));
                }
                return(Ok());
            }
            else
            {
                return(BadRequest("Void models"));
            }
        }
Пример #28
0
        public async Task <IActionResult> CreateUser(UserCreateCommand command)
        {
            CreationResult <User> createResult = User.Create(command);

            if (createResult.Ok)
            {
                var hookResult = await EventStore.AppendAll(createResult.DomainEvents);

                if (hookResult.Ok)
                {
                    await UserRepository.CreateUser(createResult.CreatedEntity);

                    return(new CreatedResult("uri", createResult.CreatedEntity));
                }
                return(new BadRequestObjectResult(hookResult.Errors));
            }
            return(new BadRequestObjectResult(createResult.DomainErrors));
        }
Пример #29
0
        public async Task UserCreateCommandTest()
        {
            var command = new UserCreateCommand("John", "Doe03");

#pragma warning disable CA2000 // Dispose objects before losing scope
            var response = await this.client.PostAsync("/users", this.CreateJsonContent(command)).ConfigureAwait(false);

#pragma warning restore CA2000 // Dispose objects before losing scope

            response.EnsureSuccessStatusCode();
            var stringResponse = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            var result = JsonConvert.DeserializeObject <UserCreateCommandResponse>(stringResponse);

            Assert.True(response.Headers.Contains("Location"));
            Assert.NotEmpty(response.Headers.GetValues("Location"));
            Assert.True(response.Headers.Contains("X-CommandId"));
            Assert.NotEmpty(response.Headers.GetValues("X-CommandId"));
            Assert.Null(result);
        }
        public async Task <IActionResult> CreateAsync(UserCreateCommand command)
        {
            try
            {
                var entryId = await _mediator.Send(command);

                return(CreatedAtRoute(
                           "UserGetById",
                           new { id = entryId },
                           null
                           ));
            }
            catch (UserCreationException ex)
            {
                return(BadRequest(ex.Message));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Пример #31
0
        public async Task Deve_Verificar_Metodo_Com_Retorno_BadRequest_Quando_Resultado_For_Falha()
        {
            // Arrange
            var command = new UserCreateCommand
            {
                Name = "mock-Name",
            };

            var expectedResult = "BadRequest";

            _moqMediator
            .Setup(p => p.Send(command, default))
            .ReturnsAsync(Result.Failure <Guid>(expectedResult));

            // Act
            var result = await GetController().CreateAsync(command);

            // Assert
            var badRequest = result as BadRequestObjectResult;

            badRequest.StatusCode.Should().Be(400);
            badRequest.Value.Should().Be(expectedResult);
        }
        public CreateResponse Post(UserCreateCommand command)
        {
            var user = new User
            {
                Id = Guid.NewGuid(),
                Email = command.Email,
                FirstName = command.FirstName,
                LastName = command.LastName,
                DisplayName = command.DisplayName,
                PasswordHash = Common.HashPassword(command.Password)
            };

            repositoryUnitOfWork.Users.Create(user);

            return new CreateResponse { Id = user.Id };
        }