Esempio n. 1
0
        public async Task ExecuteAsync()
        {
            if (Validate())
            {
                ChangePasswordResponse response = await Api.ChangePasswordAsync(new ChangePasswordRequest(Current, New));

                if (response.IsSuccess)
                {
                    Current    = null;
                    New        = null;
                    ConfirmNew = null;

                    IsChanged = true;
                    StateHasChanged();

                    await Task.Delay(2 * 1000);

                    Hide();

                    IsChanged = false;
                    StateHasChanged();
                }
                else
                {
                    ErrorMessages.AddRange(response.ErrorMessages);
                }
            }
        }
Esempio n. 2
0
        public void ChangePassword_Success(string name)
        {
            RunInitSql(name, "ConnectionStringAccounts");

            // 1. initializing the session
            InitSession initReq = new InitSession()
            {
                AccountKey   = ConfigurationManager.AppSettings["AccountKey"],
                RequestID    = "D3770630-9532-457D-8EBB-DBF99F6A23D3",
                SessionToken = null
            };

            InitSessionResponse initResp = Post <InitSession, InitSessionResponse>("InitSession", initReq);

            string sessionToken = initResp.SessionToken;

            // 2. changing password
            ChangePassword updateReq = base.PrepareRequest <ChangePassword>(name);

            updateReq.SessionToken = sessionToken;

            ChangePasswordResponse updateRes = Post <ChangePassword, ChangePasswordResponse>("ChangePassword", updateReq);

            RunFinalizeSql(name, "ConnectionStringAccounts");

            Assert.True(updateRes.Success, "Password was not updated - success = false");
            Assert.IsEmpty(updateRes.Errors, "Unexpected errors returned");
        }
        public void ChangePasswordSuccessTest_ChecksIfThePasswordIsChangedSuccessfully_VeririesThroughTheReturnedValue()
        {
            IUserRepository                      userRepository            = new MockUserRepository();
            ISecurityKeysRepository              securityKeysRepository    = new MockSecurityKeysRepository();
            IPasswordEncryptionService           passwordEncryptionService = new PasswordEncryptionService();
            IIdentityAccessPersistenceRepository persistenceRepository     = new MockPersistenceRepository(false);
            UserApplicationService               userApplicationService    = new UserApplicationService(userRepository, securityKeysRepository,
                                                                                                        passwordEncryptionService, persistenceRepository, new MockEmailService(), new PasswordCodeGenerationService());

            // Store the Securiyty Keys with the Username of the User at hand
            (securityKeysRepository as MockSecurityKeysRepository).AddSecurityKeysPair(new SecurityKeysPair(
                                                                                           new ApiKey("123456789").Value, new SecretKey("987654321").Value, "desc", 0, true));

            // We need to encrypt the password in the test case ourselves, as we are not registering the user through
            // the proper service here
            (userRepository as MockUserRepository).AddUser(new User("*****@*****.**", "linkinpark",
                                                                    passwordEncryptionService.EncryptPassword("burnitdown"), "USA", TimeZone.CurrentTimeZone, "", ""));

            User   userBeforePasswordChange = userRepository.GetUserByUserName("linkinpark");
            string passwordBeforeChange     = userBeforePasswordChange.Password;

            // Give the API key that is already stored in the Security keys repository mentioned with the User Name
            //UserValidationEssentials userValidationEssentials = new UserValidationEssentials(new Tuple<ApiKey, SecretKey>(
            //    new ApiKey("123456789"), new SecretKey("987654321")), new TimeSpan(0,0,10,0));

            ChangePasswordResponse changePasswordResponse = userApplicationService.ChangePassword(new ChangePasswordCommand(
                                                                                                      "123456789", "burnitdown", "burnitdowntwice"));

            Assert.IsTrue(changePasswordResponse.ChangeSuccessful);
            User   userAfterPasswordChange = userRepository.GetUserByUserName("linkinpark");
            string passwordAfterChange     = userAfterPasswordChange.Password;

            // Verify the old and new password do not match
            Assert.AreNotEqual(passwordBeforeChange, passwordAfterChange);
        }
Esempio n. 4
0
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
        {
            ChangePasswordResponse response = new ChangePasswordResponse();


            return(response);
        }
        /// <summary>
        /// Change Password for an existing user.
        /// </summary>
        /// <param name="request">Instance of ChangePasswordRequest</param>
        /// <returns>Instance of ChangePasswordResponse</returns>
        public async Task <ChangePasswordResponse> ChangePasswordAsync(ChangePasswordRequest request)
        {
            ChangePasswordResponse response = new ChangePasswordResponse();

            try
            {
                IdentityResult result = await UserManager.ChangePasswordAsync(request.UserId.ToString(), request.OldPassword, request.NewPassword);

                if (!result.Succeeded)
                {
                    foreach (string item in response.Errors)
                    {
                        response.Errors.Add(item);
                    }

                    response.Success = false;
                }
                else
                {
                    response.Success = true;
                }
            }
            catch (Exception e)
            {
                response.Success = false;
                response.Errors.Add(e.Message);
            }

            return(response);
        }
        public ActionResult ChangePassword(ChangePassword model)
        {
            if (ModelState.IsValid)
            {
                string          connection  = ConfigurationManager.AppSettings["InternalAPIURL"];
                var             ctx         = Request.GetOwinContext();
                ClaimsPrincipal user        = ctx.Authentication.User;
                string          accessToken = user.Claims.FirstOrDefault(x => x.Type == "AccessToken").Value;
                Guid            userID      = new Guid(user.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value);

                ChangePasswordRequest  resetRequest  = new ChangePasswordRequest(connection, accessToken, userID, model.OldPassword, model.Password1);
                ChangePasswordResponse resetResponse = resetRequest.Send();

                if (resetResponse.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    TempData["Success"] = "Your password was changed!";
                    return(RedirectToAction("Index", "Account"));
                }
                else
                {
                    TempData["Errors"] = "There was an error processing your request";
                    return(View(model));
                }
            }
            else
            {
                return(View(model));
            }
        }
        public async Task Given_change_password_endpoint_receive_valid_payload_it_should_return_200_status_code_with_user_name_in_response_body()
        {
            var changePasswordDto = new ChangePasswordDto()
            {
                CurrentPassword         = "******",
                NewPassword             = "******",
                NewPasswordConfirmation = "NewPassword",
                UserName = "******"
            };

            var changePasswordResponse = new ChangePasswordResponse()
            {
                UserName = changePasswordDto.UserName,
                Success  = true
            };

            _mediator.Setup(mock => mock.Send(It.Is <ChangePasswordCommand>(command => command.ChangePasswordDto.Equals(changePasswordDto)),
                                              It.IsAny <CancellationToken>())).ReturnsAsync(changePasswordResponse);

            var actionResult = await _credentialManagementController.ChangePassword(changePasswordDto);

            var okObjectResultWhich = actionResult.Should().BeOfType <OkObjectResult>().Which;

            okObjectResultWhich.StatusCode.Should().Be(StatusCodes.Status200OK);
            okObjectResultWhich.Value.Should().BeOfType(typeof(ChangePasswordResponse));

            var response = ((OkObjectResult)actionResult).Value as ChangePasswordResponse;

            response.UserName.Should().Be(changePasswordDto.UserName);
            response.Success.Should().BeTrue();
        }
Esempio n. 8
0
        public async Task <IActionResult> ChangePassword(ChangePasswordRequest changePasswordRequest)
        {
            var user = await _userManager.FindByEmailAsync(changePasswordRequest.Email);

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

            try
            {
                var result = await _userManager.ResetPasswordAsync(user, changePasswordRequest.Code, changePasswordRequest.Password);

                var changePasswordResponse = new ChangePasswordResponse
                {
                    IsSuccess = result.Succeeded,
                    Errors    = result.Errors.Select(x => x.Description)
                };

                return(Ok(changePasswordResponse));
            }
            catch (DbUpdateConcurrencyException) when(!_userManager.Users.AsNoTracking().Any(u => u.Email == changePasswordRequest.Email))
            {
                return(NotFound());
            }
        }
        public ChangePasswordResponse ChangePassword(ChangePasswordRequest userChangePassword)
        {
            var response = new ChangePasswordResponse();

            try
            {
                var res = UserManager.ChangePasswordAsync(userChangePassword.UserId, userChangePassword.OldPassword, userChangePassword.NewPassword);

                if (res.Result.Errors.Any())
                {
                    response.ResponseStatus  = ResponseStatus.ExpectationFailed;
                    response.ResponseMessage = MessageDescription.MessageDescription.TransactionFailed.GetDescription();
                }
                else
                {
                    response.ResponseStatus  = ResponseStatus.Ok;
                    response.ResponseMessage = MessageDescription.MessageDescription.UserStatusIsOk.GetDescription();
                }
                return(response);
            }
            catch (Exception ex)
            {
                response.ResponseStatus  = ResponseStatus.ExpectationFailed;
                response.ResponseMessage = MessageDescription.MessageDescription.TransactionFailed.GetDescription();
                Logger.ErrorException(ex.Message, ex);

                return(response);
            }
        }
        public void ChangePasswordSuccessTest_ChecksIfThePasswordIsChangedSuccessfully_VerifiesThroughTheReturnedValue()
        {
            IUserApplicationService         userApplicationService         = (IUserApplicationService)_applicationContext["UserApplicationService"];
            IRegistrationApplicationService registrationApplicationService = (IRegistrationApplicationService)_applicationContext["RegistrationApplicationService"];
            ILoginApplicationService        loginApplicationService        = (ILoginApplicationService)_applicationContext["LoginApplicationService"];

            IUserRepository userRepository = (IUserRepository)_applicationContext["UserRepository"];

            string           username         = "******";
            string           activatioNKey    = registrationApplicationService.CreateAccount(new SignupUserCommand("*****@*****.**", "linkinpark", "burnitdown", "USA", TimeZone.CurrentTimeZone, ""));
            ManualResetEvent manualResetEvent = new ManualResetEvent(false);

            userApplicationService.ActivateAccount(new ActivationCommand(activatioNKey, username, "burnitdown"));
            manualResetEvent.WaitOne(6000);
            UserValidationEssentials validationEssentials = loginApplicationService.Login(new LoginCommand(username, "burnitdown"));

            User   userBeforePasswordChange = userRepository.GetUserByUserName("linkinpark");
            string passwordBeforeChange     = userBeforePasswordChange.Password;

            ChangePasswordResponse changePasswordResponse = userApplicationService.ChangePassword(new ChangePasswordCommand(
                                                                                                      validationEssentials.ApiKey, "burnitdown", "burnitdowntwice"));

            Assert.IsTrue(changePasswordResponse.ChangeSuccessful);
            User   userAfterPasswordChange = userRepository.GetUserByUserName("linkinpark");
            string passwordAfterChange     = userAfterPasswordChange.Password;

            // Verify the old and new password do not match
            Assert.AreNotEqual(passwordBeforeChange, passwordAfterChange);
        }
        public ChangePasswordResponse ChangePassword(ChangePasswordRequest userChangePassword)
        {
            var response = new ChangePasswordResponse();

            try
            {
                var res = UserManager.ChangePasswordAsync(userChangePassword.UserId, userChangePassword.OldPassword, userChangePassword.NewPassword);

                if (res.Result.Errors.Count() > 0)
                {
                    response.ErrorList      = res.Result.Errors.ToList();
                    response.ResponseStatus = ResponseStatus.ExpectationFailed;
                }
                else
                {
                    response.ResponseStatus = ResponseStatus.Ok;
                }
                return(response);
            }
            catch (Exception ex)
            {
                response.ResponseMessage = ex.Message;
                response.ResponseStatus  = ResponseStatus.ExpectationFailed;
                return(response);
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Change Password
        /// </summary>
        /// <param name="changepwdRequest"></param>
        /// <returns></returns>
        public IHttpActionResult APSChangePassword(ChangePasswordRequest changepwdRequest)
        {
            ChangePasswordResponse response = new ChangePasswordResponse();

            using (AuthenticationBC authBC = new AuthenticationBC())
            {
                ChangePasswordModel cpModel = new ChangePasswordModel();
                cpModel.UserName           = changepwdRequest.UserName;
                cpModel.UserPassword       = changepwdRequest.UserPassword;
                cpModel.PasswordQuestionID = changepwdRequest.PasswordQuestionID;
                cpModel.PasswordQuestion   = changepwdRequest.PasswordQuestion;
                cpModel.PasswordQuesAnswer = changepwdRequest.PasswordQuesAnswer;
                cpModel.CreatedBy          = changepwdRequest.RequestedBy;
                cpModel.LastUpdatedBy      = changepwdRequest.RequestedBy;
                UserModel userModel = authBC.ChangePassword(cpModel);
                if (userModel != null)
                {
                    response.ResponseCode    = 0;
                    response.ResponseMessage = "Success";
                    response.UserInfo        = userModel;
                }
                else
                {
                    response.ResponseCode    = 1;
                    response.ResponseMessage = "Failed";
                }
                return(Ok(response));
            }
        }
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>  
        /// <param name="context"></param>
        /// <returns></returns>
        public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
        {
            ChangePasswordResponse response = new ChangePasswordResponse();


            return response;
        }
Esempio n. 14
0
        /// <summary>
        /// 更改密码
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ChangePasswordResponse ChangePassword(ChangePasswordRequest request)
        {
            var response = new ChangePasswordResponse();

            if (request.OldPassword.IsNullOrEmpty())
            {
                response.IsSuccess   = false;
                response.MessageCode = "1";
                response.MessageText = "旧密码不能为空";
                return(response);
            }

            if (request.NewPassword.IsNullOrEmpty())
            {
                response.IsSuccess   = false;
                response.MessageCode = "2";
                response.MessageText = "新密码不能为空";
                return(response);
            }

            try
            {
                var entity = _userInfoRepository.Find <UserInfoPo>(e => e.IsValid == 1 && e.Id == request.UserId);

                if (entity == null)
                {
                    response.IsSuccess   = false;
                    response.MessageCode = "2";
                    response.MessageText = "用户不存在";
                    return(response);
                }

                if (entity.Password != request.OldPassword.GetMd5())
                {
                    response.IsSuccess   = false;
                    response.MessageCode = "3";
                    response.MessageText = "旧密码有误";
                    return(response);
                }

                entity.Password = request.NewPassword.GetMd5();

                EntityLogger.UpdateEntity(entity);

                _userInfoRepository.UpdateColumns(entity, e => new
                {
                    e.Password,
                    e.UpdateUserId,
                    e.UpdateTime
                });
            }
            catch (Exception ex)
            {
                response.IsSuccess   = false;
                response.MessageCode = "-1";
                response.MessageText = ex.Message;
                LogManager.LogicLogger.ErrorFormat("更改密码出错:{0}", new { request, err = ex.ToString() }.ToJson());
            }
            return(response);
        }
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
        {
            ChangePasswordResponse response = new ChangePasswordResponse();

            context.Read();
            int targetDepth = context.CurrentDepth;

            while (context.ReadAtDepth(targetDepth))
            {
                if (context.IsStartElement)
                {
                    if (context.TestExpression("ChangePasswordResult", 2))
                    {
                        UnmarshallResult(context, response);
                        continue;
                    }

                    if (context.TestExpression("ResponseMetadata", 2))
                    {
                        response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context);
                    }
                }
            }

            return(response);
        }
Esempio n. 16
0
        public ChangePasswordResponse Process()
        {
            var response = new ChangePasswordResponse();
            var changePasswordResponseCode = ChangePassword();

            return(response.ReturnWithCode(MessageHelper.Message(changePasswordResponseCode)));
        }
Esempio n. 17
0
        public async Task <ActionResult> Manage(ManageUserViewModel model)
        {
            bool hasPassword = HasPassword();

            ViewBag.HasLocalPassword = hasPassword;
            ViewBag.ReturnUrl        = Url.Action("Manage");
            if (hasPassword)
            {
                if (ModelState.IsValid)
                {
                    ChangePasswordResponse response = await this.Membership.ChangePasswordAsync(new ChangePasswordRequest()
                    {
                        UserId      = new Guid(User.Identity.GetUserId()),
                        OldPassword = model.OldPassword,
                        NewPassword = model.NewPassword
                    });

                    if (response.Success)
                    {
                        return(RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess }));
                    }
                    else
                    {
                        AddErrors(response.Errors);
                    }
                }
            }
            else
            {
                // User does not have a password so remove any validation errors caused by a missing OldPassword field
                ModelState state = ModelState["OldPassword"];
                if (state != null)
                {
                    state.Errors.Clear();
                }

                if (ModelState.IsValid)
                {
                    AddPasswordResponse response = await this.Membership.AddPasswordAsync(new AddPasswordRequest()
                    {
                        UserId      = new Guid(User.Identity.GetUserId()),
                        NewPassword = model.NewPassword
                    });

                    if (response.Success)
                    {
                        return(RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess }));
                    }
                    else
                    {
                        AddErrors(response.Errors);
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Esempio n. 18
0
        public static ChangePasswordResponse Unmarshall(UnmarshallerContext context)
        {
            ChangePasswordResponse changePasswordResponse = new ChangePasswordResponse();

            changePasswordResponse.HttpResponse = context.HttpResponse;
            changePasswordResponse.RequestId    = context.StringValue("ChangePassword.RequestId");

            return(changePasswordResponse);
        }
    public async Task <ActionResult> ChangePassword([FromBody] Models.Request.ChangePasswordRequest request)
    {
        if (!ModelState.IsValid)
        {
            return(BadRequest(ModelState));
        }
        ChangePasswordResponse response = await _mediator.Send(new ChangePasswordCommand(request.Id, request.Password, request.NewPassword));

        return(_mapper.Map <JsonContentResult>(response));
    }
Esempio n. 20
0
        public async Task <ChangePasswordResponse> ChangePassword([FromBody] ChangePasswordRequest model)
        {
            var user = BreachUser;

            if (user == null)
            {
                return(ChangePasswordResponse.Fail("Server error in changing password"));
            }
            return(await _newUserServices.ChangePassword(model, user.Email));
        }
Esempio n. 21
0
            public void ChangePassword()
            {
                string oldPassword            = "******";
                string newPassword            = "******";
                ChangePasswordRequest request = new ChangePasswordRequest(connection, testToken, testUser, oldPassword, newPassword);

                ChangePasswordResponse response = request.Send();

                Assert.AreEqual(response.StatusCode, System.Net.HttpStatusCode.OK);
            }
Esempio n. 22
0
        public async Task <IActionResult> ChangePassword(ChangePasswordRequest request)
        {
            ChangePasswordResponse response = await _accountService.ChangePasswordAsync(request);

            if (response.IsValid())
            {
                return(Ok(response));
            }

            return(BadRequest(response.GetErrors()));
        }
Esempio n. 23
0
        public async Task <ChangePasswordResponse> ChangePassword(ChangePasswordRequest request)
        {
            ChangePasswordResponse response = await _authBusiness.ChangePassword(request);

            if (response == null)
            {
                HttpContext.Response.StatusCode = 401;
            }

            return(response);
        }
        ChangePasswordResponse Microsoft.ActiveDirectory.Management.IADAccountManagement.ChangePassword(ADSessionHandle handle, ChangePasswordRequest request)
        {
            ChangePasswordResponse       changePasswordResponse = null;
            ADDirectoryServiceConnection internalHandle         = this.GetInternalHandle(handle);

            if (internalHandle != null)
            {
                changePasswordResponse = internalHandle.ChangePassword(request);
            }
            return(changePasswordResponse);
        }
Esempio n. 25
0
        public async Task PasswordContainingUserFails()
        {
            ChangePasswordResponse changePasswordResponse = await CommonUtils.ChangePassword(NeverExpiresUser.Username,
                                                                                             NeverExpiresUser.Password,
                                                                                             "83579R!" + NeverExpiresUser.Username,
                                                                                             NeverExpiresUser.Domain,
                                                                                             NeverExpiresUser.Application);

            Assert.Equal("KS-E112", changePasswordResponse.ResponseCode);
            Assert.False(changePasswordResponse.Succeded);
        }
Esempio n. 26
0
        public async Task TooLongPasswordFails()
        {
            ChangePasswordResponse changePasswordResponse = await CommonUtils.ChangePassword(NeverExpiresUser.Username,
                                                                                             NeverExpiresUser.Password,
                                                                                             "1234567890ABCDEabcdefghi??!!!",
                                                                                             NeverExpiresUser.Domain,
                                                                                             NeverExpiresUser.Application);

            Assert.Equal("KS-E112", changePasswordResponse.ResponseCode);
            Assert.Contains("PV-E071", changePasswordResponse.CustomDataJson);
            Assert.False(changePasswordResponse.Succeded);
        }
Esempio n. 27
0
        public async void TooManyNumricCharactersPasswordFails()
        {
            ChangePasswordResponse changePasswordResponse = await CommonUtils.ChangePassword(NeverExpiresUser.Username,
                                                                                             NeverExpiresUser.Password,
                                                                                             "1234567891011Aa!",
                                                                                             NeverExpiresUser.Domain,
                                                                                             NeverExpiresUser.Application);

            Assert.Equal("KS-E112", changePasswordResponse.ResponseCode);
            Assert.Contains("PV-E011", changePasswordResponse.CustomDataJson);
            Assert.False(changePasswordResponse.Succeded);
        }
Esempio n. 28
0
        public async Task TooManyLowercaseCharactersPasswordFails()
        {
            ChangePasswordResponse changePasswordResponse = await CommonUtils.ChangePassword(NeverExpiresUser.Username,
                                                                                             NeverExpiresUser.Password,
                                                                                             "abcdefghijklmn?73",
                                                                                             NeverExpiresUser.Domain,
                                                                                             NeverExpiresUser.Application);

            Assert.Equal("KS-E112", changePasswordResponse.ResponseCode);
            Assert.Contains("PV-E021", changePasswordResponse.CustomDataJson);
            Assert.False(changePasswordResponse.Succeded);
        }
Esempio n. 29
0
        public async Task InvalidPatternPasswordFails()
        {
            ChangePasswordResponse changePasswordResponse = await CommonUtils.ChangePassword(NeverExpiresUser.Username,
                                                                                             NeverExpiresUser.Password,
                                                                                             "GRenDIzer19piP!",
                                                                                             NeverExpiresUser.Domain,
                                                                                             NeverExpiresUser.Application);

            Assert.Equal("KS-E112", changePasswordResponse.ResponseCode);
            Assert.Contains("PV-E060", changePasswordResponse.CustomDataJson);
            Assert.False(changePasswordResponse.Succeded);
        }
Esempio n. 30
0
        public async Task NoSpecialCharacterPasswordFails()
        {
            ChangePasswordResponse changePasswordResponse = await CommonUtils.ChangePassword(NeverExpiresUser.Username,
                                                                                             NeverExpiresUser.Password,
                                                                                             "KIKKa5",
                                                                                             NeverExpiresUser.Domain,
                                                                                             NeverExpiresUser.Application);

            Assert.Equal("KS-E112", changePasswordResponse.ResponseCode);
            Assert.Contains("PV-E040", changePasswordResponse.CustomDataJson);
            Assert.False(changePasswordResponse.Succeded);
        }
Esempio n. 31
0
        public async Task TooManyConsecutiveEqualCharactersPasswordFails()
        {
            ChangePasswordResponse changePasswordResponse = await CommonUtils.ChangePassword(NeverExpiresUser.Username,
                                                                                             NeverExpiresUser.Password,
                                                                                             "aaaaaabA1?",
                                                                                             NeverExpiresUser.Domain,
                                                                                             NeverExpiresUser.Application);

            Assert.Equal("KS-E112", changePasswordResponse.ResponseCode);
            Assert.Contains("PV-E050", changePasswordResponse.CustomDataJson);
            Assert.False(changePasswordResponse.Succeded);
        }
 private void onReqChangePWDSuccess(BaseWWWRequest obj)
 {
     try
     {
         if (this.needZip)
         {
             this.changePwdResponse = JsonReader.Deserialize<ChangePasswordResponse>(base.UTF8String);
         }
         else
         {
             this.changePwdResponse = JsonReader.Deserialize<ChangePasswordResponse>(base.www.text);
         }
         if (this.changePwdResponse.eid != 0)
         {
             this.onReqChangePWDFail(obj);
         }
         else
         {
             this.SaveLoginInfo();
             this.OnChangePwdSuccess();
         }
     }
     catch (Exception)
     {
         this.onReqChangePWDFail(obj);
     }
 }
Esempio n. 33
0
        public ChangePasswordResponse ChangePassword(ChangePasswordRequest request)
        {
            ChangePasswordResponse response = new ChangePasswordResponse();

            AuthToken authToken = null;

            try
            {
                Common.Helpers.ValidationHelper.ValidateRequiredField(request.AuthToken, "Auth Token");
                Common.Helpers.ValidationHelper.ValidateRequiredField(request.AntiForgeryToken, "Anti Forgery Token");
                Common.Helpers.ValidationHelper.ValidateRequiredField(request.OldPassword, "Old Password");
                Common.Helpers.ValidationHelper.ValidateRequiredField(request.NewPassword, "New Password");

                Common.Helpers.ValidationHelper.ValidateStringLength(request.OldPassword, "Old Password", Constants.MaxPasswordLength);
                Common.Helpers.ValidationHelper.ValidateStringLength(request.NewPassword, "New Password", Constants.MaxPasswordLength);

                Common.Helpers.ValidationHelper.AssertFalse(request.NewPassword.Equals(request.OldPassword), "New Password and old password are equal.");

                if (!UserController.ValidateSession(request.AuthToken, out authToken))
                {
                    throw new AuthenticationException("Authentication failed.");
                }

                UserController.ValidateAntiForgeryToken(request.AntiForgeryToken, authToken);

                ValidationHelper.ValidatePassword(request.NewPassword);

                UserController.ChangePassword(authToken.Username, request.OldPassword, request.NewPassword);
            }
            catch (AuthenticationException ex)
            {
                throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.Unauthorized);
            }
            catch (Common.Exceptions.ValidationException ex)
            {
                throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.Unauthorized);
            }
            catch (Exception ex)
            {
                ExceptionHelper.Log(ex, authToken == null ? null : authToken.Username);
                throw new WebFaultException<string>("An unknown error has occurred.", System.Net.HttpStatusCode.InternalServerError);
            }

            return response;
        }
        public IHttpActionResult ChangePassword(ChangePasswordRequest request)
        {
            var response = new ChangePasswordResponse();

            try
            {
                var isValidRequest = false;

                var memberId = request.GetMemberId();
                var member = MembershipAdapter.GetMember(memberId);

                if (request.IsValidModel())
                {
                    if (!request.PasswordsMatch())
                    {
                        request.AddError("Password", "Passwords do not match");
                    }
                }

                if (member.Authenticate(request.CurrentPassword))
                {
                    if (!request.HasErrors())
                    {
                        isValidRequest = true;
                    }
                }
                else
                {
                    request.AddError("Current password", "Current password is invalid");
                }

                if (isValidRequest)
                {
                    var memberPassword = new MemberPassword();

                    memberPassword.MemberId = member.Id;
                    memberPassword.InitializePassword(request.Password);

                    memberPassword = MembershipAdapter.UpdatePassword(memberPassword);

                    var email = new ChangePasswordEmail
                    {
                        DomainName = ConfigHelper.DomainName,
                        DomainBaseUrl = ConfigHelper.DomainBaseUrl,
                        Alias = member.Profile.Alias
                    };

                    var emailBuilder = new EmailBuilder(EmailReference.HTML.Templates.Main, EmailReference.HTML.Contents.ChangePassword);
                    var emailBody = emailBuilder.BuildBody<ChangePasswordEmail>(email);
                    var emailResult = EmailHelper.SendEmail(ConfigHelper.NoReplayEmailAddress,
                                                            ConfigHelper.DomainName,
                                                            member.Email,
                                                            member.Profile.Alias,
                                                            email.Subject,
                                                            emailBody,
                                                            true);

                    if (emailResult)
                    {
                        response.IsSuccessful = true;
                        response.StatusMessage = "Password update succeeded";
                    }
                }
                else
                {
                    response.IsSuccessful = false;
                    response.StatusMessage = "Password update was unsuccessful";
                    response.Errors.AddRange(request.GetErrors());
                }
            }
            catch (Exception ex)
            {
                request.CurrentPassword = string.Empty;
                request.Password = string.Empty;
                request.PasswordConfirm = string.Empty;

                this.Log<ChangePasswordRequest>(LogCategories.Error, request, ex.Message);

                response.IsSuccessful = false;
                response.StatusMessage = this.StatusMessageForExpection;
                response.Errors.Add(ex.Message);
            }

            return Ok(response);
        }
Esempio n. 35
0
        public string ChangePassword()
        {
            if (Signature != GetParam("sig").ToString())
            {
                ErrorCode = (int)ErrorType.API_EC_SIGNATURE;
                return "";
            }

            //如果是桌面程序则需要验证用户身份
            if (this.App.ApplicationType == (int)ApplicationType.DESKTOP)
            {
                if (Uid < 1)
                {
                    ErrorCode = (int)ErrorType.API_EC_SESSIONKEY;
                    return "";
                }
            }

            if (CallId <= LastCallId)
            {
                ErrorCode = (int)ErrorType.API_EC_CALLID;
                return "";
            }

            if (!this.CheckRequiredParams("uid,original_password,new_password,confirm_new_password"))
            {
                ErrorCode = (int)ErrorType.API_EC_PARAM;
                return "";
            }

            int uid = TypeConverter.ObjectToInt(GetParam("uid"));
            //如果是桌面程序则需要验证用户身份
            if (this.App.ApplicationType == (int)ApplicationType.DESKTOP)
            {
                if (Uid != uid)
                {
                    ErrorCode = (int)ErrorType.API_EC_PERMISSION_DENIED;
                    return "";
                }
            }

            string originalPassword = GetParam("original_password").ToString();
            string newPassword = GetParam("new_password").ToString();
            string confirmNewPassword = GetParam("confirm_new_password").ToString();

            if (newPassword != confirmNewPassword)
            {
                ErrorCode = (int)ErrorType.API_EC_PARAM;
                return string.Empty;
            }

            bool isMD5Passwd = GetParam("password_format") != null && GetParam("password_format").ToString() == "md5";

            ShortUserInfo user = Discuz.Forum.Users.GetShortUserInfo(uid);

            if (!isMD5Passwd)
            {
                originalPassword = Utils.MD5(originalPassword);
            }
            if (user.Password != originalPassword)
            {
                ErrorCode = (int)ErrorType.API_EC_PARAM;
                return string.Empty;
            }

            bool result = Discuz.Forum.Users.UpdateUserPassword(uid, newPassword, !isMD5Passwd);
            ChangePasswordResponse cpr = new ChangePasswordResponse();
            cpr.Successfull = result ? 1 : 0;
            if (Format == FormatType.JSON)
                return string.Format("\"{0}\"", result.ToString().ToLower());

            return SerializationHelper.Serialize(cpr);

        }
        public ChangePasswordResponse ChangePassword(ChangePasswordRequest request)
        {
            var response = new ChangePasswordResponse();

            try
            {
                if (WebSecurity.ChangePassword(request.UserName, request.OldPassword, request.NewPassword))
                {
                    response.Status = StatusCode.OK;
                }
                else
                {
                    response.Status = StatusCode.Unauthorized;
                }
            }
            catch (Exception ex)
            {
                response.Status = StatusCode.InternalServerError;
                this.exceptionHandler.HandleException(ex);
            }

            return response;
        }
Esempio n. 37
0
        public override bool Run(CommandParameter commandParam, ref string result)
        {
            int uid = commandParam.GetIntParam("uid");

            //如果是桌面程序则需要验证用户身份
            if (commandParam.AppInfo.ApplicationType == (int)ApplicationType.DESKTOP)
            {
                if (commandParam.LocalUid < 1)
                {
                    result = Util.CreateErrorMessage(ErrorType.API_EC_SESSIONKEY, commandParam.ParamList);
                    return false;
                }

                if (commandParam.LocalUid != uid)
                {
                    result = Util.CreateErrorMessage(ErrorType.API_EC_PERMISSION_DENIED, commandParam.ParamList);
                    return false;
                }
            }

            if (!commandParam.CheckRequiredParams("uid,original_password,new_password,confirm_new_password"))
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_PARAM, commandParam.ParamList);
                return false;
            }

            string originalPassword = commandParam.GetDNTParam("original_password").ToString();
            string newPassword = commandParam.GetDNTParam("new_password").ToString();
            string confirmNewPassword = commandParam.GetDNTParam("confirm_new_password").ToString();

            if (newPassword != confirmNewPassword)
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_PARAM, commandParam.ParamList);
                return false;
            }

            bool isMD5Passwd = commandParam.GetDNTParam("password_format") != null && commandParam.GetDNTParam("password_format").ToString().ToLower() == "md5";

            ShortUserInfo user = Discuz.Forum.Users.GetShortUserInfo(uid);
            if (!isMD5Passwd)
                originalPassword = Utils.MD5(originalPassword);

            if (user.Password != originalPassword)
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_ORI_PASSWORD_EQUAL_FALSE, commandParam.ParamList);
                return false;
            }

            bool updateSuccess = Discuz.Forum.Users.UpdateUserPassword(uid, newPassword, !isMD5Passwd);

            if (commandParam.Format == FormatType.JSON)
                result = string.Format("\"{0}\"", updateSuccess.ToString().ToLower());
            else
            {
                ChangePasswordResponse cpr = new ChangePasswordResponse();
                cpr.Successfull = updateSuccess ? 1 : 0;
                result = SerializationHelper.Serialize(cpr);
            }
            return true;
        }
        /// <summary>
        /// Change Password for an existing user.
        /// </summary>
        /// <param name="request">Instance of ChangePasswordRequest</param>
        /// <returns>Instance of ChangePasswordResponse</returns>
        public async Task<ChangePasswordResponse> ChangePasswordAsync(ChangePasswordRequest request)
        {
            ChangePasswordResponse response = new ChangePasswordResponse();

            try
            {
                IdentityResult result = await UserManager.ChangePasswordAsync(request.UserId.ToString(), request.OldPassword, request.NewPassword);

                if (!result.Succeeded)
                {
                    foreach (string item in response.Errors)
                        response.Errors.Add(item);

                    response.Success = false;
                }
                else
                {
                    response.Success = true;
                }
            }
            catch (Exception e)
            {
                response.Success = false;
                response.Errors.Add(e.Message);
            }

            return response;
        }