public async Task <string> CreateUserAsync(NewApplicationUserDTO newUser) { var uri = API.User.CreateUser(_remoteServiceBaseUrl); newUser.AdministrationUser = true; var newUserContent = new StringContent(JsonConvert.SerializeObject(newUser), System.Text.Encoding.UTF8, "application/json"); var response = await _httpClient.PostAsync(uri, newUserContent); if (response.TrySaveModelStateErrors(ref modelStateErrors)) { return(""); } return(await response.Content.ReadAsStringAsync()); // created users Id }
public async Task <IActionResult> CreateUser([FromServices] IContactService contactService, NewApplicationUserDTO model) { // check if new properties are unique if (await IsUnique(model.UserName, model.Email) == false) { return(BadRequest(ModelState)); } try { int?contactId = null; // CREATING NEW CONTACT FOR THE USER if (model.ContactAssign?.ToLower() == "new") { var id = await contactService.CreateContact(new NewContactDTO() { FirstName = model.NewContactFirstName, LastName = model.NewContactLastName, Email = model.NewContactEmail, Phone = model.NewContactPhone }); if (id < 1) // id invalid,operation didn't succeed { contactService.Validate(ModelState); if (!ModelState.IsValid) // there are model errors for creating contacts { return(BadRequest(ModelState)); } else { return(BadRequest()); } } contactId = id; } if (model.ContactAssign?.ToLower() == "existing") { contactId = model.ExistingContactId; } // add user prefix based on application var username = model.AdministrationUser ? "admin_" + model.UserName : model.ContactUser ? "contact_" + model.UserName : model.UserName; // CREATE USER var res = await _userManager.CreateAsync(new ApplicationUser() { UserName = username, Email = model.Email, PhoneNumber = model.PhoneNumber, FirstName = model.FirstName, LastName = model.LastName, CreationDate = DateTime.Now, LockoutEnd = model.Active ? DateTime.Now : DateTime.Now.AddYears(100), ContactId = contactId, ContactUser = model.ContactUser, AdministrationUser = model.AdministrationUser }); if (!res.Succeeded) // failed to create user { if (model.ContactAssign?.ToLower() == "new") // rollback contact create { await contactService.DeleteContacts(new List <int>() { contactId.Value }); } return(StatusCode((int)HttpStatusCode.InternalServerError)); } var user = await _userManager.FindByNameAsync(username); // ADD PASSWORD TO USER res = await _userManager.AddPasswordAsync(user, model.Password); if (!res.Succeeded) { if (model.ContactAssign?.ToLower() == "new") // rollback contact create { await contactService.DeleteContacts(new List <int>() { contactId.Value }); } await _userManager.DeleteAsync(user); ModelState.AddModelError("Password", string.Join(", ", res.Errors.Select(e => e.Description))); return(BadRequest(ModelState)); } return(CreatedAtAction(nameof(CreateUser), user.Id)); } catch (Exception) { return(StatusCode((int)HttpStatusCode.InternalServerError)); } }