public async Task <IHttpActionResult> CreateUser(CreateUserBinding newUser)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = new IdentityUser(newUser.ClientId, newUser.UserName)
            {
                Email     = newUser.Email,
                FirstName = newUser.FirstName,
                LastName  = newUser.LastName,
                Level     = 1,
                JoinDate  = DateTime.Now.Date,
            };

            var addUserResult = await JWTUserManager.CreateAsync(user, newUser.Password);

            if (!addUserResult.Succeeded)
            {
                return(GetErrorResult(addUserResult));
            }

            var code = await JWTUserManager.GenerateEmailConfirmationTokenAsync(user.Id);

            var callbackUrl = new Uri(Url.Link("ConfirmEmailRoute", new { userId = user.Id, code = code }));

            await JWTUserManager.SendEmailAsync(user.Id, JWTAuthServerConstants.ConfirmMailSubject,
                                                string.Format(JWTAuthServerConstants.ConfirmMailBody, callbackUrl));

            var locationHeader = new Uri(Url.Link("GetUserById", new { id = user.Id }));

            return(Created(locationHeader, EntityFactory.Create(user)));
        }
Пример #2
0
        public async Task <IActionResult> CreateUser(
            CancellationToken cancellationToken,
            [FromBody] CreateUserBinding binding,
            [FromServices] IUserRepository userRepository,
            [FromServices] IPasswordHasher passwordHasher)
        {
            var user = await userRepository.Get(binding.Id, cancellationToken);

            if (user != null)
            {
                if (!user.Name.Equals(binding.Name) ||
                    !user.Email.Equals(binding.Email))
                {
                    throw new ApiException(HttpStatusCode.Conflict, ErrorCode.UserAlreadyExists, "User already exists with other parameters");
                }
            }

            user = await userRepository.GetByName(binding.Name, cancellationToken);

            if (user != null)
            {
                throw new ApiException(HttpStatusCode.Conflict, ErrorCode.NameAlreadyExists, "Name already exists");
            }

            user = await userRepository.GetByEmail(binding.Email, cancellationToken);

            if (user != null)
            {
                throw new ApiException(HttpStatusCode.Conflict, ErrorCode.EmailAlreadyExists, "Email already exists");
            }

            var passwordHash = passwordHasher.HashPassword(binding.Password);

            user = new Domain.Admin.Users.User(binding.Id, binding.Name, binding.Email, passwordHash, binding.FirstName, binding.LastName, Enum.Parse <UserRole>(binding.Role.ToString()));

            await userRepository.Save(user);

            return(CreatedAtRoute("GetUserAdminRoute", new { id = user.Id }, null));
        }