public async Task <HttpResponseMessage> Create(HttpRequestMessage request, AppUserVm appUserVm) { if (ModelState.IsValid) { var newAppUser = new AppUser(); newAppUser.UpdateUser(appUserVm); newAppUser.CreatedDate = GetDateTimeNowUTC(); newAppUser.CreatedBy = User.Identity.GetUserId(); newAppUser.IsSystemAccount = true; try { newAppUser.Id = Guid.NewGuid().ToString(); var result = await _userManager.CreateAsync(newAppUser, appUserVm.Password); if (result.Succeeded) { var listAppUserGroup = new List <AppUserGroup>(); foreach (var group in appUserVm.Groups) { listAppUserGroup.Add(new AppUserGroup() { GroupId = group.Id, UserId = newAppUser.Id }); //add role to user var listRole = _appRoleService.GetListRoleByGroupId(group.Id); foreach (var role in listRole) { await _userManager.RemoveFromRoleAsync(newAppUser.Id, role.Name); await _userManager.AddToRoleAsync(newAppUser.Id, role.Name); } } _appGroupService.AddUserToGroups(listAppUserGroup, newAppUser.Id); return(request.CreateResponse(HttpStatusCode.OK, appUserVm)); } else { return(request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Join(",", result.Errors))); } } catch (NameDuplicatedException dex) { return(request.CreateErrorResponse(HttpStatusCode.BadRequest, dex.Message)); } catch (Exception ex) { return(request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message)); } } else { return(request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); } }
public async Task <HttpResponseMessage> Create(HttpRequestMessage request, AppUserViewModel appUserViewModel) { if (ModelState.IsValid) { var newAppUser = new AppUser(); newAppUser.UpdateUser(appUserViewModel); try { newAppUser.Id = Guid.NewGuid().ToString(); var result = await _userManager.CreateAsync(newAppUser, appUserViewModel.Password); if (result.Succeeded) { //add account to group var userGroups = new List <AppUserGroup>(); foreach (var group in appUserViewModel.AppGroups) { userGroups.Add(new AppUserGroup { UserId = newAppUser.Id, GroupId = group.Id }); //add role to user var listRole = _appRoleService.GetListRoleByGroupId(group.Id); foreach (var role in listRole) { await _userManager.RemoveFromRoleAsync(newAppUser.Id, role.Name); await _userManager.AddToRoleAsync(newAppUser.Id, role.Name); } } _appGroupService.AddUserToGroups(userGroups, newAppUser.Id); _appGroupService.Save(); return(request.CreateResponse(HttpStatusCode.OK, appUserViewModel)); } return(request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Join(",", result.Errors))); } catch (NameDuplicatedException dex) { return(request.CreateErrorResponse(HttpStatusCode.BadRequest, dex.Message)); } catch (Exception ex) { return(request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message)); } } return(request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); }