Reset user password by code.

@param string $code         Return value of self::forgot()
@param string $new_password New password for user

@return bool
424329
public function reset(string $code, string $new_password): bool
    {
        return $this->auth_repository->reset($code, $new_password);
    }
1056239
public static function Create($code, $args = null, $_ = null)
  {
    if (!is_null($args)) {
      if (!is_array($args)) {
        $args = array_slice(func_get_args(), 1);
      }
    }

    $str = static::GetNameForCode($code, $args);

    return new static($str, $code);
  }
531758
public function setNewPassword($userId, $actualPassword, $newPassword)
    {
        $user = $this->usersRepository->find($userId);
        if (!$user) {
            return false;
        }

        $newPassword = trim($newPassword);

        if (!Passwords::verify($actualPassword, $user[UserAuthenticator::COLUMN_PASSWORD_HASH])) {
            return false;
        }

        $newPassword = Passwords::hash($newPassword);

        $this->changePasswordsLogsRepository->add(
            $user,
            ChangePasswordsLogsRepository::TYPE_CHANGE,
            $user->password,
            $newPassword
        );

        $this->usersRepository->update($user, [
            'password' => $newPassword,
        ]);

        $this->emitter->emit(new UserChangePasswordEvent($user));

        return true;
    }
929351
public function actionReset($id, $code)
    {
        if (!$this->enablePasswordRecovery) {
            return $this->redirect(['/user/security/login']);
        }
        /** @var Token $token */
        $token = Token::findOne(['user_id' => $id, 'code' => $code, 'type' => Token::TYPE_RECOVERY]);
        if ($token === null || $token->isExpired || $token->user === null) {
            Yii::$app->session->setFlash('danger', Yii::t('user', 'Recovery link is invalid or expired. Please try requesting a new one.'));
            return $this->render('/message', [
                'title' => Yii::t('user', 'Invalid or expired link'),
                'module' => $this->module
            ]);
        }
        /** @var RecoveryForm $model */
        $model = new RecoveryForm(['scenario' => 'reset']);
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(Yii::$app->getRequest()->post()) && $model->resetPassword($token)) {
            return $this->redirect(['/user/security/login']);
        }

        return $this->render('reset', ['model' => $model]);
    }
306568
def reset_password(token):
    """"""

    expired, invalid, user = reset_password_token_status(token)

    if not user or invalid:
        invalid = True
        do_flash(*get_message('INVALID_RESET_PASSWORD_TOKEN'))

    if expired:
        send_reset_password_instructions(user)
        do_flash(*get_message('PASSWORD_RESET_EXPIRED', email=user.email,
                              within=_security.reset_password_within))
    if invalid or expired:
        return redirect(url_for('forgot_password'))

    form = _security.reset_password_form()

    if form.validate_on_submit():
        after_this_request(_commit)
        update_password(user, form.password.data)
        do_flash(*get_message('PASSWORD_RESET'))
        return redirect(get_url(_security.post_reset_view) or
                        get_url(_security.login_url))

    return _security.render_template(
        config_value('RESET_PASSWORD_TEMPLATE'),
        reset_password_form=form,
        reset_password_token=token,
        **_ctx('reset_password')
    )
1314671
public function reset(string $key) : Response
    {
        //is the key empty or does it existe?
        if (empty($key) || !$userData = Users::findFirst(['user_activation_forgot = :key:', 'bind' => ['key' => $key]])) {
            throw new Exception(_('This Key to reset password doesn\'t exist'));
        }

        // Get the new password and the verify
        $newPassword = trim($this->request->getPost('new_password', 'string'));
        $verifyPassword = trim($this->request->getPost('verify_password', 'string'));

        //Ok let validate user password
        $validation = new Validation();
        $validation->add('new_password', new PresenceOf(['message' => _('The password is required.')]));
        $validation->add('new_password', new StringLength(['min' => 8, 'messageMinimum' => _('Password is too short. Minimum 8 characters.')]));

        $validation->add('new_password', new Confirmation([
            'message' => _('Passwords do not match.'),
            'with' => 'verify_password',
        ]));

        //validate this form for password
        $messages = $validation->validate($this->request->getPost());
        if (count($messages)) {
            foreach ($messages as $message) {
                throw new Exception($message);
            }
        }

        // Check that they are the same
        if ($newPassword == $verifyPassword) {
            // Has the password and set it
            $userData->user_activation_forgot = '';
            $userData->user_active = 1;
            $userData->password = Users::passwordHash($newPassword);

            // Update
            if ($userData->update()) {
                //log the user out of the site from all devices
                $session = new Sessions();
                $session->end($userData);

                $this->sendEmail($userData, 'reset');

                return $this->response(_('Congratulations! You\'ve successfully changed your password.'));
            } else {
                throw new Exception(current($userData->getMessages()));
            }
        } else {
            throw new Exception(_('Password are not the same'));
        }
    }
940912
def set_lock_code(ctx, lock_code, new_lock_code, clear, generate, force):
    

    dev = ctx.obj['dev']

    def prompt_new_lock_code():
        return prompt_lock_code(prompt='Enter your new lock code')

    def prompt_current_lock_code():
        return prompt_lock_code(prompt='Enter your current lock code')

    def change_lock_code(lock_code, new_lock_code):
        lock_code = _parse_lock_code(ctx, lock_code)
        new_lock_code = _parse_lock_code(ctx, new_lock_code)
        try:
            dev.write_config(
                device_config(
                    config_lock=new_lock_code),
                reboot=True,
                lock_key=lock_code)
        except Exception as e:
            logger.error('Changing the lock code failed', exc_info=e)
            ctx.fail('Failed to change the lock code. Wrong current code?')

    def set_lock_code(new_lock_code):
        new_lock_code = _parse_lock_code(ctx, new_lock_code)
        try:
            dev.write_config(
                device_config(
                    config_lock=new_lock_code),
                reboot=True)
        except Exception as e:
            logger.error('Setting the lock code failed', exc_info=e)
            ctx.fail('Failed to set the lock code.')

    if generate and new_lock_code:
        ctx.fail('Invalid options: --new-lock-code conflicts with --generate.')

    if clear:
        new_lock_code = CLEAR_LOCK_CODE

    if generate:
        new_lock_code = b2a_hex(os.urandom(16)).decode('utf-8')
        click.echo(
            'Using a randomly generated lock code: {}'.format(new_lock_code))
        force or click.confirm(
            'Lock configuration with this lock code?', abort=True, err=True)

    if dev.config.configuration_locked:
        if lock_code:
            if new_lock_code:
                change_lock_code(lock_code, new_lock_code)
            else:
                new_lock_code = prompt_new_lock_code()
                change_lock_code(lock_code, new_lock_code)
        else:
            if new_lock_code:
                lock_code = prompt_current_lock_code()
                change_lock_code(lock_code, new_lock_code)
            else:
                lock_code = prompt_current_lock_code()
                new_lock_code = prompt_new_lock_code()
                change_lock_code(lock_code, new_lock_code)
    else:
        if lock_code:
            ctx.fail(
                'There is no current lock code set. '
                'Use --new-lock-code to set one.')
        else:
            if new_lock_code:
                set_lock_code(new_lock_code)
            else:
                new_lock_code = prompt_new_lock_code()
                set_lock_code(new_lock_code)
11439
public function setCode( $code = null)
	{
		// Require that the response be unlocked before changing it
		$this->requireUnlocked();
		$this->status = new Status($code);
		return $this;
	}
26399
public function codeUpdate($code, $new_code, $card_id)
    {
        if (empty($code) || empty($new_code)) {
            $this->setError('缺少错误');

            return false;
        }

        $queryStr             = [];
        $queryStr['code']     = $code;
        $queryStr['new_code'] = $new_code;
        if (!empty($card_id)) {
            $queryStr['card_id'] = $card_id;
        }

        $this->apitype = 'card';
        $this->module  = 'code';

        $res = $this->_post('update', $queryStr);

        return $res;
    }
868313
function user_update_password($user, $newpassword) {
        $user = get_complete_user_data('id', $user->id);
        // This will also update the stored hash to the latest algorithm
        // if the existing hash is using an out-of-date algorithm (or the
        // legacy md5 algorithm).
        return update_internal_user_password($user, $newpassword);
    }
1246697
public function setCode($code) {
        $this->code = trim($code);
        $this->codeLength = strlen($this->code);
        return $this;
    }
1289791
public function findUserByPersistenceCode($code)
    {
        $persistence = $this->findByPersistenceCode($code);

        if ($persistence)
        {
            return $persistence->getUser();
        }

        return false;
    }
1265374
static public function password( $userID, $newPassword )
    {
        $user = eZUser::fetch( $userID );

        if ( $user instanceof eZUser )
        {
            $login   = $user->attribute( 'login' );
            $type    = eZUser::hashType();
            $site    = $user->site();
            $newHash = $user->createHash( $login, $newPassword, $site, $type );
            $user->setAttribute( 'password_hash', $newHash );
            $user->setAttribute( 'password_hash_type', $type );
            $user->store();

            // "Draft" must be in sync with the PersistentObject
            self::updateUserDraft( $user );
			
            eZContentCacheManager::clearContentCacheIfNeeded( $userID );

            return array( 'status' => true );
        }
        else
        {
            eZDebug::writeError( "Failed to change password of user $userID (could not fetch user)", __METHOD__ );
            return array( 'status' => false );
        }
    }
261752
public function PasswordReset($UserID = '', $PasswordResetKey = '') {
      if (!is_numeric($UserID)
          || $PasswordResetKey == ''
          || $this->UserModel->GetAttribute($UserID, 'PasswordResetKey', '') != $PasswordResetKey
         ) $this->Form->AddError('Failed to authenticate your password reset request. Try using the reset request form again.');

      if ($this->Form->ErrorCount() == 0) {
         $User = $this->UserModel->GetID($UserID, DATASET_TYPE_ARRAY);
         if ($User) {
            $User = ArrayTranslate($User, array('UserID', 'Name', 'Email'));
            $this->SetData('User', $User);
         }
      }
      
      if ($this->Form->ErrorCount() == 0
         && $this->Form->IsPostBack() === TRUE
      ) {
         $Password = $this->Form->GetFormValue('Password', '');
         $Confirm = $this->Form->GetFormValue('Confirm', '');
         if ($Password == '')
            $this->Form->AddError('Your new password is invalid');
         else if ($Password != $Confirm)
            $this->Form->AddError('Your passwords did not match.');

         if ($this->Form->ErrorCount() == 0) {
            $User = $this->UserModel->PasswordReset($UserID, $Password);
            Gdn::Session()->Start($User->UserID, TRUE);
//            $Authenticator = Gdn::Authenticator()->AuthenticateWith('password');
//            $Authenticator->FetchData($Authenticator, array('Email' => $User->Email, 'Password' => $Password, 'RememberMe' => FALSE));
//            $AuthUserID = $Authenticator->Authenticate();
				Redirect('/');
         }
      }
      $this->Render();
   }
1101052
public function resetpasswordAction()
    {
        $errors  = array();
        $form    = $this->createResetRequestForm();
        $request = $this->getRequest();

        if ($key = $this->_getParam('key')) {
            $user = $this->loader->getUserLoader()->getUserByResetKey($key);

            if ($user->hasValidResetKey()) {
                // Signal the reqset required so the maxage check is disabled while validating
                $user->setPasswordResetRequired(true);

                $form = $user->getChangePasswordForm(array('askOld' => false, 'askCheck' => true, 'labelWidthFactor' => $this->labelWidthFactor));

                $result = $user->authenticate(null, false);
                if (! $result->isValid()) {
                    $this->addMessage($result->getMessages());
                    $this->addMessage($this->_('For that reason you cannot reset your password.'));
                    return;
                }

                if (! $request->isPost()) {
                    $this->accesslog->logChange($request, sprintf("User %s opened valid reset link.", $user->getLoginName()));
                }
            } else {
                if (! $request->isPost()) {
                    if ($user->getLoginName()) {
                        $message = sprintf("User %s used old reset key.", $user->getLoginName());
                    } else {
                        $message = sprintf("Someone used a non existent reset key.", $user->getLoginName());
                    }
                    $this->accesslog->logChange($request, $message);

                    if ($user->hasPassword() || (! $user->isActive())) {
                        $errors[] = $this->_('Your password reset request is no longer valid, please request a new link.');
                    } else {
                        $errors[] = $this->_('Your password input request is no longer valid, please request a new link.');
                    }
                }

                if ($user->isActive()) {
                    $form->getUserNameElement()->setValue($user->getLoginName());
                    $form->getOrganizationElement()->setValue($user->getBaseOrganizationId());
                }
            }
        }

        if ($request->isPost() && $form->isValid($request->getPost())) {

            if ($form instanceof \Gems_User_Form_ResetRequestForm) {
                $user = $form->getUser();

                $result = $user->authenticate(null, false);
                if (! $result->isValid()) {
                    $this->addMessage($result->getMessages());
                    $this->addMessage($this->_('For that reason you cannot request a password reset.'));
                    return;
                }

                $errors = $this->sendUserResetEMail($user);
                if ($errors) {
                    $this->accesslog->logChange(
                            $request,
                            sprintf(
                                    "User %s requested reset password but got %d error(s). %s",
                                    $form->getUserNameElement()->getValue(),
                                    count($errors),
                                    implode(' ', $errors)
                                    )
                            );

                } else {
                    // Everything went OK!
                    $this->addMessage($this->_(
                            'We sent you an e-mail with a reset link. Click on the link in the e-mail.'
                            ));

                    $this->accesslog->logChange($request);

                    if ($this->returnToLoginAfterReset) {
                        $this->setCurrentOrganizationTo($user);
                        $this->currentUser->gotoStartPage($this->menu, $request);
                    }
                }

            } elseif ($form instanceof \Gems_User_Form_ChangePasswordForm) {
                $this->addMessage($this->_('New password is active.'));

                // User set before this form was initiated
                $user->setAsCurrentUser();

                /**
                 * Log the login
                 */
                $this->accesslog->logChange($request, $this->_("User logged in through reset password."));
        		$user->gotoStartPage($this->menu, $this->getRequest());
                return;
            }

        }
        $form->populate($request->getParams());

        $this->displayResetForm($form, $errors);
    }
372479
function overwriteValueWithCode($code)
    {
        $this->replacedState = self::VALUE_REPLACED;
        $this->phpVariable = null;
        $this->setPHPCode($code);
    }
192084
public function updateCode($code, $card_id, $new_code)
    {
        if (empty($code) || empty($card_id) || $new_code) {
            return false;
        }

        $result = $this->httpPost(static::WECHAT_CARD_CODE_UPDATE_URL . 'access_token=' . $this->getAccessToken(), [
            'code' => $code,
            'card_id' => $card_id,
            'new_code' => $new_code
        ]);

        return isset($result['errmsg']) && $result['errmsg'] === 'ok' ? true : false;
    }