示例#1
0
        public async Task <IActionResult> ChangeEmail([FromBody] ChangeEmailDto model)
        {
            var user = await this.GetUserByIdentityAsync(_userManager);

            if (user == null)
            {
                return(Unauthorized());
            }

            if (user.Email == model.NewEmail)
            {
                return(BadRequest("This email is the same as yours"));
            }

            var resultChangeEmail = await _userManager.ChangeEmailAsync(user, model.NewEmail, model.EmailToken);

            if (!resultChangeEmail.Succeeded)
            {
                return(BadRequest(new
                {
                    Message = "Can't change email",
                    resultChangeEmail.Errors
                }));
            }

            return(Ok(_mapper.Map <UserDto>(user)));
        }
示例#2
0
        public async Task <IActionResult> ChangeEmail([FromBody] ChangeEmailDto model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = await _userManager.FindByIdAsync(model.Id);

            if (user == null)
            {
                return(NotFound("user not found"));
            }

            var result = await _userManager.ChangeEmailAsync(user, model.Email);

            if (result.Succeeded)
            {
                return(Ok(model));
            }

            AddErrorsToModelState(result);

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            return(StatusCode(500));
        }
示例#3
0
        public async Task ChangeEmailAsync(ChangeEmailDto dto)
        {
            var a    = _httpContextAccessor.HttpContext.User;
            var user = await _userManager.GetUserAsync(a);

            var token = await _userManager.GenerateChangeEmailTokenAsync(user, dto.NewEmail);

            await _userManager.ChangeEmailAsync(user, dto.NewEmail, token);
        }
示例#4
0
        public async Task <IActionResult> ChangeEmail(ChangeEmailDto emailDto)
        {
            var changeEmail = await mediator.Send(new ChangeEmailUerCommand { Email = emailDto.Email, Id = emailDto.Id });

            if (changeEmail.Success)
            {
                return(Ok());
            }
            return(BadRequest(changeEmail.ErrorMessage));
        }
示例#5
0
        public void Execute(ChangeEmailDto request)
        {
            if (Validate(request))
            {
                var user = _context.Users.Find(request.UserId);

                user.DateUpdated = DateTime.Now;
                user.Email       = request.NewEmail;

                _context.SaveChanges();
            }
        }
示例#6
0
        public bool Validate(ChangeEmailDto request)
        {
            if (!_context.Users.Any(x => x.Id == request.UserId))
            {
                throw new EntityNotFoundException($"User with id: {request.UserId}");
            }

            if (_context.Users.Any(x => x.Email == request.NewEmail))
            {
                throw new EntityAlreadyExistsException($"Email address");
            }

            return(true);
        }
示例#7
0
        public async Task <IActionResult> ChangeEmail([FromBody] ChangeEmailDto model)
        {
            // Trim model
            model = model.TrimProperties();

            // Check model state
            if (!ModelState.IsValid)
            {
                return(BadRequest(new RequestMessageResponse()
                {
                    Success = false, Message = "Invalid data model"
                }));
            }

            // Get user
            var user = await _identityService.GetCurrentPersonIdentityAsync();

            if (user == null)
            {
                return(BadRequest(new RequestMessageResponse()
                {
                    Success = false, Message = "Invalid user"
                }));
            }


            // Change email
            var token = await _userManager.GenerateChangeEmailTokenAsync(user, model.NewEmail);

            var result = await _userManager.ChangeEmailAsync(user, model.NewEmail, token);

            if (result.Succeeded)
            {
                await _userManager.SetUserNameAsync(user, model.NewEmail);

                return(new OkObjectResult(new RequestMessageResponse()
                {
                    Success = true, Message = "Email changed"
                }));
            }
            // Change password failed
            return(BadRequest(new RequestMessageResponse()
            {
                Success = false, Message = "Change email failed"
            }));
        }
示例#8
0
        public async Task <IActionResult> ChangeEmail([FromBody] ChangeEmailDto changeEmailDto)
        {
            var user = await _userManager.GetByIdentityAsync(this);

            if (user == null)
            {
                return(Unauthorized());
            }

            var changeEmailResult = await _userManager.ChangeEmailAsync(user, changeEmailDto.NewEmail, changeEmailDto.Token);

            if (!changeEmailResult.Succeeded)
            {
                return(BadRequest("Can't change email"));
            }

            return(Ok(_mapper.Map <User, ExternalUserDto>(user)));
        }
示例#9
0
 public IActionResult ChangeEmail(int id, [FromForm] ChangeEmailDto dto)
 {
     try
     {
         dto.UserId = id;
         _editUserEmail.Execute(dto);
         return(Ok());
     }
     catch (EntityNotFoundException e)
     {
         return(NotFound(e.Message));
     }
     catch (EntityAlreadyExistsException e)
     {
         return(Conflict(e.Message));
     }
     catch (Exception e)
     {
         return(StatusCode(500, e.Message));
     }
 }
示例#10
0
        public async Task <IActionResult> ChangeEmail([FromBody] ChangeEmailDto profile, string id)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                string userId = User.Claims.First(c => c.Type == "UserID").Value;
                var    user   = (Person)await unitOfWork.UserManager.FindByIdAsync(userId);

                string userRole = User.Claims.First(c => c.Type == "Roles").Value;

                if (String.IsNullOrEmpty(userRole))
                {
                    return(Unauthorized());
                }

                if (user == null)
                {
                    return(NotFound("User not found"));
                }

                var result = await unitOfWork.ProfileRepository.ChangeEmail(user, profile.Email);

                if (result.Succeeded)
                {
                    return(Ok(result));
                }

                return(BadRequest(result.Errors));
            }
            catch (Exception)
            {
                return(StatusCode(500, "Failed to save changes"));
            }
        }
示例#11
0
        public async Task <IActionResult> ChangeEmail(ChangeEmailDto dto)
        {
            await _usersService.ChangeEmailAsync(dto);

            return(Ok());
        }
 public IViewComponentResult Invoke(ChangeEmailDto input) => View(input);
示例#13
0
        public async Task <IActionResult> ChangeEmail([FromBody] ChangeEmailDto dto)
        {
            ChangeEmailDtoValidator validator = new ChangeEmailDtoValidator();
            ValidationResult        result    = await validator.ValidateAsync(dto);

            if (result.IsValid)
            {
                #region 驗證重複

                if (await _userManager.Users.AnyAsync(x => x.Email == dto.NewEmail))
                {
                    result.Errors.Add(new ValidationFailure("newEmail", "新的電子郵件已經被使用"));
                    return(BadRequest(result.Errors));
                }

                #endregion

                var userId = User.Claims
                             .Single(p => p.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value;
                var user = await _userManager.FindByIdAsync(userId);

                await using (var transaction = await _dbContext.Database.BeginTransactionAsync())
                {
                    try
                    {
                        var oldEmail = user.Email;
                        if (await _userManager.ReplaceClaimAsync(user, new Claim(ClaimTypes.Email, oldEmail), new Claim(ClaimTypes.Email, dto.NewEmail)) != IdentityResult.Success)
                        {
                            throw new DbUpdateException();
                        }
                        user.Email           = dto.NewEmail;
                        user.NormalizedEmail = dto.NewEmail.ToUpper();
                        user.EmailConfirmed  = false;
                        _dbContext.Users.Update(user);
                        if (await _dbContext.SaveChangesAsync() < 0)
                        {
                            throw new DbUpdateException();
                        }

                        #region UpdateSecurity

                        var oldSecurityStamp = user.SecurityStamp;
                        if (await _userManager.UpdateSecurityStampAsync(user) != IdentityResult.Success)
                        {
                            throw new DbUpdateException();
                        }
                        if (await _userManager.ReplaceClaimAsync(user, new Claim(ClaimTypes.Sid, oldSecurityStamp), new Claim(ClaimTypes.Sid, user.SecurityStamp)) != IdentityResult.Success)
                        {
                            throw new DbUpdateException();
                        }

                        #endregion

                        await transaction.CommitAsync();
                    }
                    catch (DbUpdateException)
                    {
                        await transaction.RollbackAsync();

                        throw;
                    }
                }

                #region 寄信

                var link = $"{_configuration["FrontendUrl"]}/account/email/confirm" +
                           $"?userId={Uri.EscapeDataString(user.Id)}" +
                           $"&token={Uri.EscapeDataString(await _userManager.GenerateEmailConfirmationTokenAsync(user))}";

                await _mailService.SendEmailConfirmAsync(user.Email, user.Email, link, false);

                #endregion

                return(NoContent());
            }
            return(BadRequest(result.Errors));
        }