public async Task <IActionResult> UpdateUser(int idUser, UserForUpdateDto userUpdateDto) { if (idUser == int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value) && (userUpdateDto.Activo == false)) { throw new Exception($"No se puede dejar inactivo al usuario logeado actualmente "); } var userFromRepo = await _repo.GetUser(idUser); _mapper.Map(userUpdateDto, userFromRepo); _repo.Update(userFromRepo); if (await _repo.SaveAll()) { return(NoContent()); } throw new Exception($"Actualizando usuario {idUser} fallo"); }
public IResult Update(UserForUpdateDto userForUpdate) { if (userForUpdate.NewPassword.Length > 0) { if (!HashingHelper.VerifyPasswordHash(userForUpdate.Password, userForUpdate.PasswordHash, userForUpdate.PasswordSalt)) { return(new ErrorDataResult <User>(Messages.PasswordError)); } byte[] passwordHash, passwordSalt; HashingHelper.CreatePasswordHash(userForUpdate.NewPassword, out passwordHash, out passwordSalt); userForUpdate.PasswordHash = passwordHash; userForUpdate.PasswordSalt = passwordSalt; var user = new User { Id = userForUpdate.Id, FirstName = userForUpdate.FirstName, LastName = userForUpdate.LastName, Email = userForUpdate.Email, PasswordHash = userForUpdate.PasswordHash, PasswordSalt = userForUpdate.PasswordSalt }; _userDal.Update(user); return(new SuccessResult(Messages.UserUpdated)); } else { var user = new User { Id = userForUpdate.Id, FirstName = userForUpdate.FirstName, LastName = userForUpdate.LastName, Email = userForUpdate.Email, PasswordHash = userForUpdate.PasswordHash, PasswordSalt = userForUpdate.PasswordSalt }; _userDal.Update(user); return(new SuccessResult(Messages.UserUpdated)); } }
public async Task <IActionResult> UpdateUser(UserForUpdateDto userForUpdate) { userForUpdate.Username = userForUpdate.Username.ToLower(); if (!await _repo.UserExists(userForUpdate.Username)) { return(BadRequest("User does not exist.")); } var userToUpdate = new User { Username = userForUpdate.Username, Email = userForUpdate.Email, Phone = userForUpdate.Phone, DateOfBirth = userForUpdate.DateOfBirth, Country = userForUpdate.Country, SelfDescription = userForUpdate.SelfDescription, City = userForUpdate.City }; var updatedUser = await _repo.UpdateUser(userToUpdate, userForUpdate.Password); return(Ok(updatedUser)); }
public async Task <IActionResult> UpdateUser(int id, UserForUpdateDto userForUpdateDto) { /* * We have access to the User object via the http context (as the user sends up a token) * and this contains details about the users claims. */ if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var userFromRepo = await this.repo.GetUser(id); this.mapper.Map(userForUpdateDto, userFromRepo); if (await this.repo.SaveAll()) { return(Ok(userForUpdateDto)); } throw new Exception($"Updating user: {id} failed on save."); }
public async Task <IActionResult> UpdateUser(int id, UserForUpdateDto userForUpdateDto) { //if id passed does not match user id in a token - return unauthorized. if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var userFromRepo = await _repo.GetUser(id); _mapper.Map(userForUpdateDto, userFromRepo); //will map(update) user from repo (database) with user dto if (await _repo.SaveAll()) { return(NoContent()); } else { throw new System.Exception($"Updating user {id} failed on save"); } }
public async Task <IActionResult> UpdateUser(int id, UserForUpdateDto userForUpdateDto) { // khi client ban request len server se kem theo token, // thuc hien compare id get tu path url vs id trong token trong request if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } // get user theo id var userFromRepo = await _repo.GetUser(id); // update data form userForUpdateDto to userFromRepo _mapper.Map(userForUpdateDto, userFromRepo); // save changes if (await _repo.SaveAll()) { return(NoContent()); } throw new Exception($"Updating user {id} failed on save"); }
public async Task <IActionResult> UpdateUser(int id, UserForUpdateDto userForUpdate) { try { if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var userFromepo = await _repo.GetUser(id); _mapper.Map(userForUpdate, userFromepo); if (await _repo.SaveAll()) { return(NoContent()); } } catch (Exception ex) { throw ex; } return(NoContent()); }
public async Task <IActionResult> UpdateUser(string id, UserForUpdateDto userForUpdateDto) { var user = await _db._UserRepository.GetByIdAsync(id); var userRromRepo = _mapper.Map(userForUpdateDto, user); _db._UserRepository.Update(userRromRepo); if (await _db.SaveAcync() > 0) { return(NoContent()); } else { _logger.LogError($"کاربر {userForUpdateDto.Name} اپدیت نشد"); return(BadRequest(new ReturnMessage() { status = false, title = "خطا", message = $"ویرایش برای کاربر {userForUpdateDto.Name} انجام نشد." })); } }
public async Task <IActionResult> UpdateUser(int id, UserForUpdateDto userForUpdateDto) { //check if the user is trying to update their own profile if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } //if so, we bring the user as it is on the DB var userFromRepo = await _repo.GetUser(id); //and we run a mapping from the new user to the user on the DB _mapper.Map(userForUpdateDto, userFromRepo); //save if (await _repo.SaveAll()) { return(NoContent()); } throw new Exception($"Updating user {id} failed on save"); }
public async Task <IActionResult> UpdateUser(int id, UserForUpdateDto userForUpdateDto) { try { if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var userFromRepo = await _repo.GetUser(id); _mapper.Map(userForUpdateDto, userFromRepo); if (await _repo.SaveAll()) { return(NoContent()); } throw new Exception($"Updating user {id} failed to save"); } catch (Exception) { throw; } }
public async Task <IActionResult> UpdateUser(int id, UserForUpdateDto userForUpdateDto) { if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var userFromRepo = await _repo.GetUser(id, true); if (userFromRepo == null) { throw new System.Exception($"user {id} not found!"); } _mapper.Map(userForUpdateDto, userFromRepo); if (await _repo.SaveAll()) { return(NoContent()); } throw new System.Exception($"Updating user {id} failed on save"); }
public async Task <IActionResult> UpdateUser(int id, UserForUpdateDto userForUpdateDto) { //check if user is authorized if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } // get the user var mainUser = await _repo.GetUser(id, true); //map the data from the Dto source to main user class _mapper.Map(userForUpdateDto, mainUser); //save changes and check if saved successfully if (await _repo.SaveAll()) { return(NoContent()); } throw new Exception($"Updating user with {id} failed on save."); }
public async Task <IActionResult> UpdateUser(int id, [FromBody] UserForUpdateDto userForUpdateDto) { // checked if the modelstate if valid if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // get the id of the user that sent request to the api var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); // get the user from repo var userFromRepo = await _repo.GetUser(id); if (userFromRepo == null) { return(NotFound($"Could not find user of ID of {id}")); } // compare the currentuserid with userfromrepo id to make user it match // so that the only current loggin user can update their profile if (currentUserId != userFromRepo.Id) { return(Unauthorized()); } // map _mapper.Map(userForUpdateDto, userFromRepo); if (await _repo.SaveAll()) { // success return no content with the status code of 204 return(NoContent()); } throw new Exception($"Updating user {id} failed on save"); }
public async Task <IActionResult> UpdateUser([FromBody] UserForUpdateDto payload, Guid id, Guid UserId) { ApiResponse <UserForUpdateDto> response = new ApiResponse <UserForUpdateDto>(); try { if (!response.Errors.Any()) { var userFromRepo = await _userSrv.GetUser(id); if (userFromRepo == null) { return(BadRequest(new { errorList = "Invalid User Id" })); } var currentUserId = User.FindFirst(ClaimTypes.NameIdentifier).Value; if (currentUserId != userFromRepo.Email) { return(BadRequest(new { errorList = "UnAuthorized" })); } (List <ValidationResult> Result, UserForUpdateDto User)errorResult = await _userSrv.UpdateUser(payload, UserId); if (errorResult.Result.Any()) { return(BadRequest(new { errorList = $"{errorResult.Result.FirstOrDefault().ErrorMessage}" })); } else { response.Code = ApiResponseCodes.OK; response.Description = $"User Updated Successfully."; } } } catch (Exception ex) { return(BadRequest(ex.Message)); } return(Ok(response)); }
public async Task <IActionResult> UpdateUser(int id, [FromBody] UserForUpdateDto userForUpdateDto) { if (!ModelState.IsValid) { _logger.LogWarning(LoggingEvents.InvalidModelState, "UpdateUser method detected invalid model state"); return(BadRequest(ModelState)); } var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); var userFromRepo = await _repo.GetUser(id); if (userFromRepo == null) { return(NotFound($"Could not find user with ID {id}")); } if (userFromRepo.Id != currentUserId) { _logger.LogWarning(LoggingEvents.InvalidUserId, $"Requested update for user ID {id} doesn't match that of login in user ID" + currentUserId); return(Unauthorized()); } _mapper.Map(userForUpdateDto, userFromRepo); if (!await _repo.SaveAll()) { // If can't successfully save to DB this is a major error var errMsg = $"Couldn't update DB for user ID {id}"; _logger.LogError(LoggingEvents.DBSaveFailed, errMsg); throw new Exception(errMsg); } return(NoContent()); }
//[TransactionScopeAspect] public IDataResult <UserForUpdateDto> Update(UserForUpdateDto userForUpdate) { var currentUser = _userService.GetById(userForUpdate.UserId); var user = new User { Id = userForUpdate.UserId, Email = userForUpdate.Email, FirstName = userForUpdate.FirstName, LastName = userForUpdate.LastName, PasswordHash = currentUser.Data.PasswordHash, PasswordSalt = currentUser.Data.PasswordSalt }; byte[] passwordHash, passwordSalt; if (userForUpdate.Password != "") { HashingHelper.CreatePasswordHash(userForUpdate.Password, out passwordHash, out passwordSalt); user.PasswordHash = passwordHash; user.PasswordSalt = passwordSalt; } _userService.Update(user); var customer = new Customer { CustomerId = userForUpdate.CustomerId, UserId = userForUpdate.UserId, CompanyName = userForUpdate.CompanyName, FindexPoint = userForUpdate.FindexPoint }; _customerService.Update(customer); return(new SuccessDataResult <UserForUpdateDto>(userForUpdate, Messages.CustomerUpdated)); }
public async Task <IActionResult> CompleteRegister([FromBody] UserForUpdateDto userForUpdateDto) { userForUpdateDto.Username = userForUpdateDto.Username.ToLower(); if (!await _repo.UserExists(userForUpdateDto.Username)) { return(BadRequest("Username nonexistent")); } var userToCreate = new User { Username = userForUpdateDto.Username, Company = userForUpdateDto.Company, Telephone = userForUpdateDto.Telephone, LastName = userForUpdateDto.LastName, FirstName = userForUpdateDto.FirstName, Address = userForUpdateDto.Address, AboutMe = userForUpdateDto.AboutMe }; var createUser = await _repo.CompleteRegister(userToCreate, userForUpdateDto.Password); return(StatusCode(201)); }
public async Task <IActionResult> UpdateUser(int id, UserForUpdateDto userForUpdateDto) { // check if the user upding the profile is the logged in user if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } //get user from repo var userFromRepo = await _repo.GetUser(id); // write values from userForUpdateDto to userFRomRepo _mapper.Map(userForUpdateDto, userFromRepo); //persist if (await _repo.SaveAll()) { return(NoContent()); } // if somethign goes wrong throw new System.Exception($"Updating user {id} failed on save"); }
public IActionResult UpdateUser(int id, [FromBody] UserForUpdateDto userForUpdate) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (!_urlShortenerRepository.UserExists(id)) { return(NotFound()); } var userEntity = _urlShortenerRepository.GetUser(id); _mapper.Map(userForUpdate, userEntity); //_cityInfoRepository.UpdatePointOfInterestForCity(cityId, pointOfInterestEntity); _urlShortenerRepository.Save(); return(NoContent()); }
public async Task <User> UpdateUserData(UserForUpdateDto user) { var userFromDb = await _context.Users.Include(c => c.Country).FirstOrDefaultAsync(u => u.Id == user.Id); if (userFromDb != null) { userFromDb.Name = user.Name; userFromDb.Surname = user.Surname; userFromDb.Phone = user.Phone; userFromDb.PostalCode = user.PostalCode; userFromDb.Street = user.Street; userFromDb.City = user.City; userFromDb.CountryId = user.CountryId; } var result = await _context.SaveChangesAsync(); var country = await _context.Countries.FirstOrDefaultAsync(c => c.Id == user.CountryId); userFromDb.Country = country; return(userFromDb); }
public async Task <IActionResult> UpdateUser(int id, UserForUpdateDto userForUpdateDto) { // Check token ID if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } // Get the user from the Repo var userFromRepo = await _repo.GetUser(id); // Update values from DTO and upate them on the repo user _mapper.Map(userForUpdateDto, userFromRepo); //Save changes if (await _repo.SaveAll()) { return(NoContent()); } throw new Exception($"Updatating user with {id} failed while saving."); }
public async Task <IActionResult> UpdateUser(int id, UserForUpdateDto userForUpdateDto) { //get id from logged in users token if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } //get user from db var userFromRepo = await datingRepo.GetUser(id); //mao map from dto to repo mapper.Map(userForUpdateDto, userFromRepo); //if db saved return no content if (await datingRepo.SaveAll()) { return(NoContent()); } //if there was error during save throw error throw new Exception($"მომხმარებლი {id} ვერ შეინახა"); }
public async Task <IActionResult> UpdateUser(int id, UserForUpdateDto userForUpdateDto) { if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var userFromDb = await _repo.GetUser(id); if (userFromDb == null) { return(NotFound()); } _mapper.Map(userForUpdateDto, userFromDb); if (await _repo.SaveAll()) { return(NoContent()); } throw new Exception($"Failed to update user with id {userFromDb.Id}"); }
public async Task <IActionResult> UpdateUser(int id, UserForUpdateDto userForUpdateDto) { // check that the user updating the profile matches the token that the server is receiving // compare id of path to the user id in the token if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var userFromRepo = await _repo.GetUser(id); _mapper.Map(userForUpdateDto, userFromRepo); // Only the fields in the UserForUpdateDto model are updated. Other fields are unchanged. if (await _repo.SaveAll()) { return(NoContent()); } // if we don't return NoContent (successful save), something went wrong throw new Exception($"Updating user {id} failed on save"); }
public async Task <IActionResult> UpdateUser(int id, [FromBody] UserForUpdateDto userForUpdateDto) { if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var userFromRepo = await _repo.GetUser(id); if (userFromRepo == null) { return(Ok("record from repo is null")); } _mapper.Map(userForUpdateDto, userFromRepo); if (await _repo.SaveAll()) { return(NoContent()); } throw new Exception($"Updating user ID:{id} failed on save"); }
public async Task <IActionResult> UpdateUser(int id, UserForUpdateDto userForUpdateDto) { //check if the passed id = the one from the decodedToken, and if the guy putting //the update is the current user(associated with the executing action): Only you //can update your own information! //ClaimsPrincipal ControllerBase.User {get;} //Get the ClaimsPrincipal if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var userFromRepo = await _userService.GetUser(id, true); _mapper.Map(userForUpdateDto, userFromRepo); if (await _userService.SaveAll()) { return(NoContent()); } return(StatusCode(StatusCodes.Status500InternalServerError)); }
public async Task <IHttpActionResult> UpdateUser(int id, [FromBody] UserForUpdateDto userForUpdateDto) { //var currentUserId = int.Parse(ClaimsPrincipal.Current.Claims.First(c => c.Type == ClaimTypes.NameIdentifier).Value); //var userFromRepoClaim = await _repo.GetUser(currentUserId); //userFromRepoClaim.LastActive = DateTime.Now; //db.Entry(userFromRepoClaim).State = EntityState.Modified; // data is updated in database //await db.SaveChangesAsync(); var userFromRepo = await _repo.GetUser(id); Mapper.Map(userForUpdateDto, userFromRepo); db.Entry(userFromRepo).State = EntityState.Modified; // data is updated in database await db.SaveChangesAsync(); // changes is commiteed in data base return(StatusCode(HttpStatusCode.NoContent)); throw new Exception($"Updating user {id} failed on save"); }
public async Task <IActionResult> UpdateUser(Guid id, UserForUpdateDto userForUpdate) { if (!ChcekUserIsAuthorized(id)) { _logger.LogError($"Unauthorzied user with userid: {id}"); return(Unauthorized()); } var userFromRepo = await _repository.GetUserAsync(id); _mapper.Map(userForUpdate, userFromRepo); _repository.UpdateUser(userFromRepo); if (await _repository.SaveAsync()) { _logger.LogInfo($"Update for user with id: {id} successful"); return(NoContent()); } _logger.LogError($"Error to update the user with id {id}"); throw new Exception($"Updating user with {id} failed to save"); }
public async Task <Result <User> > Update(int userRequestId, bool isAdmin, UserForUpdateDto userForUpdateDto) { if (isAdmin || userRequestId == userForUpdateDto.Id) { var user = await _userManager.Users.FirstOrDefaultAsync(u => u.Id.Equals(userForUpdateDto.Id)); if (user != null) { User.Update(user, userForUpdateDto.FirstName, userForUpdateDto.LastName, userForUpdateDto.Introduction); var result = await _userManager.UpdateAsync(user); Result <User> .CreateResult(user, result.GetErrorsDescription()); } return(Result <User> .CreateResult(user, new HashSet <string> { "Usuário não encontrado." })); } return(Result <User> .CreateResult(null, new HashSet <string> { "Permissão negada." })); }
public async Task <IActionResult> UpdateUser(Guid id, UserForUpdateDto userForUpdateDto) { if (id != userForUpdateDto.Id) { return(BadRequest("User ID missmatch")); } var userFound = await _users.GetUserById(id); if (userFound == null) { return(NotFound($"User with the Id = {id} was not found")); } var result = await _users.UpdateUser(userForUpdateDto); if (result.Succeeded) { return(Ok()); } return(StatusCode(StatusCodes.Status500InternalServerError, "Error Updating Data")); }