public async Task <IActionResult> Put(int id, [FromBody] Region entity) { try { if (id < 1 || !isValid(entity)) { return(new BadRequestResult()); } return(Ok(await shared.Update(id, entity))); } catch (Exception ex) { return(await HandleExceptionAsync(ex)); } }
public async Task <IActionResult> Put(int id, [FromBody] Manager entity) { Manager ObjectToBeUpdated = null; try { if (string.IsNullOrEmpty(entity.FirstName) || string.IsNullOrEmpty(entity.LastName) || string.IsNullOrEmpty(entity.Email)) { return(new BadRequestObjectResult(new Error(errorEnum.e_badRequest))); // This returns HTTP 404 } //fetch object, assuming it exists ObjectToBeUpdated = agent.GetUser(id); if (ObjectToBeUpdated == null) { return(new NotFoundObjectResult(entity)); } // managers cannot edit other managers, just themselves if (!User.IsInRole("Administrator") && Convert.ToInt32(User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.PrimarySid)?.Value) != id) { return(new UnauthorizedResult());// return HTTP 401 } ObjectToBeUpdated.FirstName = entity.FirstName; ObjectToBeUpdated.LastName = entity.LastName; ObjectToBeUpdated.Username = entity.Username; ObjectToBeUpdated.OtherInfo = entity.OtherInfo ?? entity.OtherInfo; ObjectToBeUpdated.PrimaryPhone = entity.PrimaryPhone ?? entity.PrimaryPhone; ObjectToBeUpdated.SecondaryPhone = entity.SecondaryPhone ?? entity.SecondaryPhone; ObjectToBeUpdated.Email = entity.Email; ObjectToBeUpdated.RegionManagers = entity.RegionManagers; //admin can only change role if (User.IsInRole(Role.Admin) && !string.IsNullOrEmpty(entity.Role)) { ObjectToBeUpdated.Role = entity.Role; } //change password if needed if (!string.IsNullOrEmpty(entity.Password) && !Cryptography .VerifyPassword(entity.Password, ObjectToBeUpdated.Salt, ObjectToBeUpdated.Password)) { ObjectToBeUpdated.Salt = Cryptography.CreateSalt(); ObjectToBeUpdated.Password = Cryptography.GenerateSHA256Hash(entity.Password, ObjectToBeUpdated.Salt); }//end if var x = await shared.Update(id, ObjectToBeUpdated); // add new region managers to DB if (ObjectToBeUpdated.RegionManagers != null) { var existingRMs = agent.GetUser(id).RegionManagers; foreach (var rm in ObjectToBeUpdated.RegionManagers) { if (!existingRMs.Any(r => r.ManagerID == rm.ManagerID && r.RegionID == rm.RegionID)) { await shared.Add(rm); } } } //remove info not relevant x.Salt = null; x.Password = null; return(Ok(x)); } catch (Exception ex) { return(await HandleExceptionAsync(ex)); } }