コード例 #1
0
        public async Task <IActionResult> ChangePassword(ChangePasswordDto dto)
        {
            try
            {
                var response = await _client.ChangePasswordAsync(dto);

                if (!string.IsNullOrEmpty(response.Error))
                {
                    if (response.Error == ErrorMessages.UserNotFound)
                    {
                        return(HandleNotFound(response.Error));
                    }

                    return(HandleBadRequest(response.Error));
                }

                return(HandleOk());
            }
            catch (Exception e)
            {
                return(HandleBadGateway(e.Message));
            }
        }
コード例 #2
0
        public async Task ChangePasswords_ServiceReturnsErrors_ReturnsBadRequestObjectResult()
        {
            var mock = AutoMock.GetLoose();
            var changePasswordDto = new ChangePasswordDto();
            var errors            = new Dictionary <string, string> {
                { "Password", "Invalid current password" }
            };

            mock.Mock <IUserService>().Setup(x => x.UpdatePassword("id", changePasswordDto)).ReturnsAsync(errors);
            var controller = mock.Create <UserController>();

            controller.ControllerContext = new ControllerContext {
                HttpContext = new DefaultHttpContext()
            };
            var claims = new ClaimsPrincipal();

            claims.AddIdentity(new ClaimsIdentity(new [] { new Claim(ClaimTypes.PrimarySid, "id") }));
            controller.ControllerContext.HttpContext.User = claims;

            var result = await controller.ChangePassword(changePasswordDto);

            var resultErrors = Assert.IsType <BadRequestObjectResult>(result);
        }
コード例 #3
0
        public async Task UpdatePassword_ChangePasswordReturnsErrors_ReturnsProperDictionary()
        {
            var managerMock = GetUserManagerMock();
            var user        = GetValidUser();
            var passwordDto = new ChangePasswordDto {
                OldPassword = "******", NewPassword = "******", NewPasswordConfirm = "321"
            };

            managerMock.Setup(x => x.FindByIdAsync("Admin")).ReturnsAsync(user);
            var errors = new[]
            { new IdentityError {
                  Code = "Password", Description = "Provided password is too short"
              } };

            managerMock.Setup(x => x.ChangePasswordAsync(user, "123", "321")).ReturnsAsync(IdentityResult.Failed(errors));
            var mapper  = new Mock <IMapper>();
            var service = new UserService(managerMock.Object, mapper.Object);

            var result = await service.UpdatePassword("Admin", passwordDto);

            Assert.Single(result);
            Assert.Equal("Password", result.First().Key);
        }
コード例 #4
0
ファイル: UserAppService.cs プロジェクト: seanz617/AceAdmin
        public async Task <bool> ChangePassword(ChangePasswordDto input)
        {
            if (_abpSession.UserId == null)
            {
                throw new UserFriendlyException("请在登录后进行密码修改");
            }
            long userId = _abpSession.UserId.Value;
            var  user   = await _userManager.GetUserByIdAsync(userId);

            var loginAsync = await _logInManager.LoginAsync(user.UserName, input.CurrentPassword, shouldLockout : false);

            if (loginAsync.Result != AbpLoginResultType.Success)
            {
                throw new UserFriendlyException("输入密码与原密码不匹配,请重新尝试或联系管理员");
            }
            if (!Regex.IsMatch(input.NewPassword, AccountAppService.PasswordRegex))
            {
                throw new UserFriendlyException("密码不能为空");
            }
            user.Password = _passwordHasher.HashPassword(user, input.NewPassword);
            CurrentUnitOfWork.SaveChanges();
            return(true);
        }
コード例 #5
0
        public async Task GivenUserIsAuthenticatedAndConfirmationPasswordDoesNotMatch_WhenChangingPassword_ThenReturnsError()
        {
            // Arrange
            var payload = new ChangePasswordDto
            {
                CurrentPassword = Factory.IdentityClearPassword,
                ConfirmPassword = "******",
                Password        = "******",
            };

            Factory.IdentityRepositoryMock.Setup(m => m.Get(Factory.Identity.Id)).Returns(Task.FromResult(Factory.Identity));

            // Act
            var response = await AuthenticatedPost(Endpoint, payload);

            // Assert
            response.ShouldBeSuccessful();

            var envelope = await response.ShouldBeVoid();

            envelope.ShouldBeUnsuccessful();
            envelope.Error.Code.Should().Be((uint)ChangePasswordResult.PasswordsDontMatch);
        }
コード例 #6
0
        public async Task <bool> ChangePassword(ChangePasswordDto input)
        {
            if (_abpSession.UserId == null)
            {
                throw new UserFriendlyException("Please log in before attemping to change password.");
            }
            long userId = _abpSession.UserId.Value;
            var  user   = await _userManager.GetUserByIdAsync(userId);

            var loginAsync = await _logInManager.LoginAsync(user.UserName, input.CurrentPassword, shouldLockout : false);

            if (loginAsync.Result != AbpLoginResultType.Success)
            {
                throw new UserFriendlyException("Your 'Existing Password' did not match the one on record.  Please try again or contact an administrator for assistance in resetting your password.");
            }
            if (!new Regex(AccountAppService.PasswordRegex).IsMatch(input.NewPassword))
            {
                throw new UserFriendlyException("Passwords must be at least 8 characters, contain a lowercase, uppercase, and number.");
            }
            user.Password = _passwordHasher.HashPassword(user, input.NewPassword);
            CurrentUnitOfWork.SaveChanges();
            return(true);
        }
コード例 #7
0
        public APIResult ChangePassword([FromBody] ChangePasswordDto obj)
        {
            try
            {
                List <UserInfo> userList = masterService.GetUserInfo("", "", obj.UserId, "", "", "", "", "");
                if (userList != null && userList.Count > 0)
                {
                    if (userList[0].Password != obj.sOldPassword)
                    {//原密码不正确
                        return(new APIResult()
                        {
                            Status = false, Body = "原密码不正确"
                        });
                    }
                    accountService.UpdatePassword(obj.UserId, obj.sNewPassword);
                }
                else
                {
                    return(new APIResult()
                    {
                        Status = false, Body = "用户不存在"
                    });
                }

                return(new APIResult()
                {
                    Status = true, Body = ""
                });
            }
            catch (Exception ex)
            {
                return(new APIResult()
                {
                    Status = false, Body = "密码修改失败! " + ex.Message
                });
            }
        }
コード例 #8
0
 public JsonResult ChangePassword(ChangePasswordDto model, string returnUrl)
 {
     ViewBag.returnUrl = returnUrl;
     if (!ModelState.IsValid)
     {
         return(Json(null));
     }
     if (UnitOfWork.UserBL.ChangePassword(model.Email, model.Password, model.NewPassword, out string errorMessage))
     {
         if (UnitOfWork.Complete() > 0)
         {
             var redirect = returnUrl ?? "/";
             return(Json(new
             {
                 Ok = true,
                 Message = "Password changed successully",
                 Redirect = redirect,
             }));
         }
         else
         {
             return(Json(new
             {
                 Ok = false,
                 Message = "Failed to change password",
             }));
         }
     }
     else
     {
         return(Json(new
         {
             Ok = false,
             Message = errorMessage,
         }));
     }
 }
コード例 #9
0
        public ResultDto AuthenticationChangePassword(ChangePasswordDto dtoChangePassword)
        {
            ResultDto dtoresult = new ResultDto();

            dtoresult.ResultCod = Convert.ToInt16(AuthenticationCode.AccessDenied);
            dtoresult.Message   = "AccessDenied";

            try
            {
                dtoChangePassword.UserName    = Crypto.DecryptStringAes(dtoChangePassword.UserName);
                dtoChangePassword.Password    = Crypto.DecryptStringAes(dtoChangePassword.Password);
                dtoChangePassword.NewPassword = Crypto.DecryptStringAes(dtoChangePassword.NewPassword);

                BasicAuthenticationDto dtoBasicAuthentication = GetBasicAuthentication(dtoChangePassword.UserName, dtoChangePassword.Password, dtoChangePassword.IdCompany, dtoChangePassword.IdApplication, dtoChangePassword.Token);

                if (dtoBasicAuthentication.AuthenticationCod == Convert.ToInt16(AuthenticationCode.Success) && !string.IsNullOrEmpty(dtoChangePassword.NewPassword))
                {
                    UserApplicationDto dtoUserApplication = new UserApplicationDto();
                    dtoUserApplication.UserName     = dtoChangePassword.UserName;
                    dtoUserApplication.UserPassword = dtoChangePassword.Password;
                    dtoUserApplication.State        = true;
                    dtoUserApplication = UserApplicationRepository.GetUserApplication(dtoUserApplication).First();

                    dtoUserApplication.UserPassword = dtoChangePassword.NewPassword.ToUpper();
                    UserApplicationRepository.SaveUserApplication(dtoUserApplication);
                    dtoresult.ResultCod = Convert.ToInt16(AuthenticationCode.Success);
                    dtoresult.Message   = "Success";
                }
            }
            catch (Exception)
            {
                dtoresult.ResultCod = Convert.ToInt16(AuthenticationCode.AccessDenied);
                dtoresult.Message   = "AccessDenied";
            }

            return(dtoresult);
        }
コード例 #10
0
        /// <summary>
        /// Changes the password of a user with the given id. Ensured the current password is valid.
        /// </summary>
        /// <param name="dto">Contains a user's id, new password and current password.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">Throws if <paramref name="dto"/> is null.</exception>
        /// <exception cref="NotFoundException">Throws if the user with the given id cannot be found.</exception>
        /// <exception cref="ValidationException">Throws if the user's current password cannot be verified or if the new password is not valid.</exception>
        public async Task ChangePasswordAsync(ChangePasswordDto dto)
        {
            if (dto == null)
            {
                throw new ArgumentNullException(nameof(dto));
            }

            _logger.LogDebug("Changing password for user '{0}'", dto.Id);

            var user = await _repository.FindByIdAsync(dto.Id);

            if (user == null)
            {
                _logger.LogDebug("User with id '{0}' could not be found.", dto.Id);

                throw new NotFoundException(ErrorMessages.UserNotFound);
            }

            user.UpdatePassword(dto, _passwordHasher, _passwordValidator);

            await _repository.SaveChangesAsync();

            _logger.LogDebug("Successfully change user's password.");
        }
コード例 #11
0
        public async Task <ActionResult> ChangePassword([FromBody] ChangePasswordDto model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.ValidationState));
            }

            try
            {
                var id   = _authRepo.GetCurrentUser();
                var user = await _authRepo.GetUserById(id);

                if (user == null)
                {
                    return(NotFound(new { Error = "user not found" }));
                }
                bool isPasswordValid = await _authRepo.IsPasswordValid(model, user);

                if (!isPasswordValid)
                {
                    return(BadRequest(new { Error = "incorrect password" }));
                }
                bool success = await _authRepo.ResetPassword(model, user);

                if (!success)
                {
                    return(StatusCode(StatusCodes.Status500InternalServerError, "An Error Occured while resetting password"));
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e.InnerException?.ToString() ?? e.Message);
                return(StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error"));
            }
            return(Ok(new { Succeded = true }));
        }
コード例 #12
0
ファイル: UserService.cs プロジェクト: doanhuybinh90/Eimt
        public ChangePasswordResult ChangePassword(ChangePasswordDto changePasswordDto)
        {
            var user = repository.FindUserByEmail(changePasswordDto.Email);

            if (user == null)
            {
                return(new ChangePasswordResult {
                    Message = "User Doesn't exists"
                });
            }
            if (!user.IsEmailConfirmed)
            {
                return(new ChangePasswordResult {
                    Message = "User account is not confirmed"
                });
            }
            var result = user.ChangePassword(changePasswordDto.OldPassword, changePasswordDto.Password);

            if (result.Success)
            {
                unitOfWork.Commit();
            }
            return(new ChangePasswordResult(result));
        }
コード例 #13
0
ファイル: UsersController.cs プロジェクト: nesfit/Coffee
        public async Task <ActionResult> ChangePassword(ChangePasswordDto newPwDto, [FromServices] IUserPasswordAuthenticator userPwAuthenticator, [FromServices] IMeansValueHasher pwHasher)
        {
            var userId = User.GetUserId();
            var user   = await _usersService.GetUser(userId);

            if (user is null)
            {
                return(NotFound());
            }

            var authResult = await userPwAuthenticator.AuthenticateAsync(user.EmailAddress, newPwDto.OldPassword);

            if (authResult is null)
            {
                return(BadRequest(new ErrorDto("invalid_old_password", "The old password does not match. Please try again.")));
            }

            if (newPwDto.NewPassword != newPwDto.NewPasswordAgain)
            {
                return(BadRequest(new ErrorDto("invalid_new_passwords", "The new passwords do not match. Please try again.")));
            }

            return(await SendAndHandleOperationCommand(new UpdateAuthenticationMeansValue(authResult.MeansId, pwHasher.Hash(newPwDto.NewPassword))));
        }
コード例 #14
0
        public ActionResult ChangePassword(ChangePasswordDto dto)
        {
            var id = getGuid(User.Identity.GetUserId());

            if (dto.wantEditpassword)
            {
                var u = UserManager.ChangePassword(id, dto.oldPassword, dto.newPassword);
                if (u.Succeeded)
                {
                    var             user    = _UserService.GetById(id);
                    RegisterUserDto userDto = new RegisterUserDto();
                    userDto.PassWordExpired = false;
                    var result = _UserService.Edit(userDto, id);
                    return(RedirectToAction("index", "Home"));
                }
                else
                {
                    ViewBag.error = "حدث خطأ تأكد من كلمة المرور الخاصة بك وكون الكلمة الجديدة من 6 حروف";
                    return(View(dto));
                }
            }
            _UserService.editForAdm(id, dto.fullname, dto.UserName);
            return(RedirectToAction("index", "Home"));
        }
コード例 #15
0
ファイル: UsersController.cs プロジェクト: lllukasll/InterOn
        public IActionResult ChangePassword(int userId, [FromBody] ChangePasswordDto changePasswordDto)
        {
            if (_userService.GetUserById(userId) == null)
            {
                return(BadRequest("Brak użytkownika o id : " + userId));
            }

            if (changePasswordDto == null)
            {
                return(BadRequest("Nie podano danych"));
            }

            if (changePasswordDto.OldPassword == null || changePasswordDto.NewPassword == null ||
                changePasswordDto.NewPassword2 == null)
            {
                return(BadRequest("Niepoprawne dane"));
            }

            if (changePasswordDto.NewPassword != changePasswordDto.NewPassword2)
            {
                return(BadRequest("Hasła nie zgadzają się"));
            }

            if (_userService.CheckPassword(changePasswordDto.OldPassword, userId))
            {
                return(BadRequest("Złe haslo"));
            }

            if (_userService.ChangePassword(userId, changePasswordDto))
            {
                return(Ok());
            }

            return(BadRequest());
            //return Ok("Zmiana hasła : " + userId + " | OldPassword : "******" | NewPassword : "******" | NewPassword2 : " + changePasswordDto.NewPassword2);
        }
コード例 #16
0
        public async Task <IActionResult> ChangePassword(ChangePasswordDto changePasswordDto)
        {
            if (int.Parse(changePasswordDto.Id) != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

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

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

            var result = await _userManager.ChangePasswordAsync(user,
                                                                changePasswordDto.OldPassword, changePasswordDto.NewPassword);

            if (!result.Succeeded)
            {
                return(BadRequest("Failed to change password"));
            }

            return(Ok());
        }
コード例 #17
0
        public async Task <IActionResult> ChangePassword([FromBody] ChangePasswordDto changepasswordDto)
        {
            if (ModelState.IsValid)
            {
                var userDto = await _authService.GetUserAsync(User);

                if (userDto == null)
                {
                    return(BadRequest());
                }
                var result = await _authService.ChangePasswordAsync(userDto.Id, changepasswordDto);

                if (!result.Succeeded)
                {
                    return(BadRequest(_resourceForErrors["Change-PasswordProblems"]));
                }
                _authService.RefreshSignInAsync(userDto); //тут
                return(Ok(_resourceForErrors["ChangePasswordConfirmation"]));
            }
            else
            {
                return(BadRequest(_resourceForErrors["ModelIsNotValid"]));
            }
        }
コード例 #18
0
        public async Task <IActionResult> ChangePassword(ChangePasswordDto changePasswordDto)
        {
            var user = await _userManager.FindByIdAsync(changePasswordDto.id);

            if (user == null)
            {
                return(BadRequest("Could not find user"));
            }

            var newPassword = changePasswordDto.newPassword;
            var result      = await _userManager.ChangePasswordAsync(user, "wing9fake", newPassword);



            if (result.Succeeded)
            {
                return(Ok(new
                {
                    token = GenerateJwtToken(user)
                }));
            }

            return(Unauthorized("Something went wrong. Please try changing your password again."));
        }
コード例 #19
0
        public async Task <bool> ChangePassword(ChangePasswordDto input)
        {
            if (_abpSession.UserId == null)
            {
                throw new UserFriendlyException("Please log in before attemping to change password.");
            }

            long userId = _abpSession.UserId.Value;
            var  user   = await _userManager.GetUserByIdAsync(userId);

            string tenancyName = null;
            int?   tenantId    = AbpSession.TenantId;

            if (tenantId.HasValue)
            {
                Tenant tenant = await _tenantManager.GetByIdAsync(tenantId.Value);

                tenancyName = tenant.TenancyName;
            }

            var loginAsync = await _logInManager.LoginAsync(user.UserName, input.CurrentPassword, tenancyName : tenancyName, shouldLockout : false);

            if (loginAsync.Result != AbpLoginResultType.Success)
            {
                throw new UserFriendlyException(L("ExistingPasswordWrong"));
            }

            //if (!new Regex(AccountAppService.PasswordRegex).IsMatch(input.NewPassword))
            //{
            //    throw new UserFriendlyException("Passwords must be at least 8 characters, contain a lowercase, uppercase, and number.");
            //}

            user.Password = _passwordHasher.HashPassword(user, input.NewPassword);
            CurrentUnitOfWork.SaveChanges();
            return(true);
        }
コード例 #20
0
        public HttpResponseMessage ChangePassword(ChangePasswordDto changePasswordDto)
        {
            try
            {
                var userId   = changePasswordDto.UserId;
                var password = changePasswordDto.Password;
                KeyValuePair <HttpStatusCode, string> response;
                var user = Components.UsersController.GetUser(userId, PortalSettings, UserInfo, out response);
                if (user == null)
                {
                    return(Request.CreateErrorResponse(response.Key, response.Value));
                }

                var controller = Components.UsersController.Instance;
                controller.ChangePassword(PortalId, userId, password);

                return(Request.CreateResponse(HttpStatusCode.OK, new { Success = true }));
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
            }
        }
コード例 #21
0
        public IResult ChangePassword(ChangePasswordDto changePasswordDto)
        {
            byte[] passwordHash, passwordSalt;
            var    userToCheck = _userService.GetByUserId(changePasswordDto.UserId).Data;

            if (userToCheck == null)
            {
                return(new ErrorResult(Messages.UserNotFound));
            }
            if (!HashingHelper.VerifyPasswordHash(changePasswordDto.OldPassword, userToCheck.PasswordHash, userToCheck.PasswordSalt))
            {
                return(new ErrorResult(Messages.PasswordError));
            }

            if (changePasswordDto.OldPassword == changePasswordDto.NewPassword)
            {
                return(new ErrorResult(Messages.PasswordSame));
            }
            HashingHelper.CreatePasswordHash(changePasswordDto.NewPassword, out passwordHash, out passwordSalt);
            userToCheck.PasswordHash = passwordHash;
            userToCheck.PasswordSalt = passwordSalt;
            _userService.Update(userToCheck);
            return(new SuccessResult(Messages.ChangePassword));
        }
コード例 #22
0
        public IActionResult ChangePassword([FromBody] ChangePasswordDto changePassword)
        {
            _userService.ChangePassword(changePassword);

            return(new NoContentResult());
        }
コード例 #23
0
 public IActionResult Post([FromBody] ChangePasswordDto dto, [FromServices] IChangeUserPassword command)
 {
     dto.UserId = _actor.Id;
     _executor.ExecuteCommand(command, dto);
     return(StatusCode(StatusCodes.Status204NoContent));
 }
コード例 #24
0
        public async Task <ApiResult> ChangePassword(int UserId, ChangePasswordDto changePasswordDto, CancellationToken cancellationToken)
        {
            await _userService.ResetPasswordByAdmin(UserId, changePasswordDto.NewPassword);

            return(Ok());
        }
コード例 #25
0
        public async Task <UnifyResponseDto> ChangePasswordAsync([FromBody] ChangePasswordDto passwordDto)
        {
            await _userSevice.ChangePasswordAsync(passwordDto);

            return(UnifyResponseDto.Success("密码修改成功"));
        }
コード例 #26
0
 public void ResetPassword(ChangePasswordDto userInfo)
 {
 }
コード例 #27
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="model"></param>
 public ChangePasswordCommand(ChangePasswordDto model)
 {
     Model = model;
 }
コード例 #28
0
        public ResultDto ChangePassword([FromBody] ChangePasswordDto passwordDto)
        {
            _userSevice.ChangePassword(passwordDto);

            return(ResultDto.Success("密码修改成功"));
        }
コード例 #29
0
 public Task <ServiceResult> ChangePasswordAsync(ChangePasswordDto model, int userId)
 {
     throw new NotImplementedException();
 }
コード例 #30
0
 public Task ChangePassword(ChangePasswordDto password)
 {
     throw new NotImplementedException();
 }