public async Task <IActionResult> ChangeUserEmailAsync([FromBody] ChangeUserEmailRequest model) { if (!ModelState.IsValid) { return(BadRequest()); } try { var result = await _accountService.ChangeUserEmailTask(User.Identity.Name, model); if (!result) { return(StatusCode(401, "Email is already exist")); } return(StatusCode(200)); } catch (UserNotFoundException ex) { return(StatusCode(404, ex.Message)); } catch (Exception ex) { _logger.Error(ex); return(StatusCode(500, "Internal server error")); } }
public async Task <bool> ChangeUserEmailTask(string identityName, ChangeUserEmailRequest model) { using (var context = _serviceProvider.GetService <DatabaseContext>()) { var user = await context.Users.FirstOrDefaultAsync(x => x.Id == identityName); if (user == null) { throw new UserNotFoundException(); } if (model.NewEmail == user.Email || model.OldEmail == model.NewEmail) { return(false); } user.Email = model.NewEmail; await context.SaveChangesAsync(); } return(true); }