Allow a user to reset his password after he had forgotten it.

@return void
332366
public function resetpasswordAction() {
        $this->view->title = __('reset password page title');
        $authVars = Garp_Auth::getInstance()->getConfigValues();
        $activationCode = $this->getRequest()->getParam('c');
        $activationEmail = $this->getRequest()->getParam('e');
        $expirationColumn = $authVars['forgotpassword']['activation_code_expiration_date_column'];

        $userModel = new Model_User();
        $activationCodeClause = 'MD5(CONCAT(' .
                $userModel->getAdapter()->quoteIdentifier(
                    $authVars['forgotpassword']['activation_token_column']
                ) . ',' .
                'MD5(email),' .
                'MD5(' . $userModel->getAdapter()->quote($authVars['salt']) . '),' .
                'MD5(id)' .
            ')) = ?'
        ;
        $select = $userModel->select()
            // check if a user matches up to the given code
            ->where($activationCodeClause, $activationCode)
            // check if the given email address is part of the same user record
            ->where('MD5(email) = ?', $activationEmail);

        $user = $userModel->fetchRow($select);
        if (!$user) {
            $this->view->error = __('reset password user not found');
            return;
        }
        if (strtotime($user->{$expirationColumn}) < time()) {
            $this->view->error = __('reset password link expired');
            return;
        }
        if (!$this->getRequest()->isPost()) {
            return;
        }
        $password = $this->getRequest()->getPost('password');
        if (!$password) {
            $this->view->formError = sprintf(__('%s is a required field'), ucfirst(__('password')));
            return;
        }

        if (!empty($authVars['forgotpassword']['repeatPassword'])
            && !empty($authVars['forgotpassword']['repeatPasswordField'])
        ) {
            $repeatPasswordField = $this->getRequest()->getPost(
                $authVars['forgotpassword']['repeatPasswordField']
            );
            if ($password != $repeatPasswordField) {
                $this->view->formError = __('the passwords do not match');
                return;
            }
        }

        // Update the user's password and send him along to the login page
        $updateClause = $userModel->getAdapter()->quoteInto('id = ?', $user->id);
        $userModel->update(
            array(
            'password' => $password,
            $authVars['forgotpassword']['activation_token_column'] => null,
            $authVars['forgotpassword']['activation_code_expiration_date_column'] => null
            ), $updateClause
        );
        $this->_helper->flashMessenger(__($authVars['resetpassword']['success_message']));
        $this->_redirect('/g/auth/login');
    }
1077529
public function resetPasswordAction()
    {
        if($user = $this->identity()) {
            return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
        }
    
        $user = new User;
        $form = $this->getUserFormHelper()->createUserForm($user, 'ResetPassword');
        $message = null;
        if($this->getRequest()->isPost()) {
            $form->setValidationGroup('csrf', 'captcha');
            $form->setData($this->getRequest()->getPost());
            if($form->isValid()) {
                $data = $form->getData();
                $usernameOrEmail = $this->params()->fromPost('usernameOrEmail');
                $entityManager = $this->getEntityManager();
                $user = $entityManager->createQuery("SELECT u FROM CsnUser\Entity\User u WHERE u.email = '$usernameOrEmail' OR u.username = '$usernameOrEmail'")->getResult(\Doctrine\ORM\Query::HYDRATE_OBJECT);
                $user = $user[0];
    
                if(isset($user)) {
                    try {
                        $user->setRegistrationToken(md5(uniqid(mt_rand(), true)));
                        $fullLink = $this->getBaseUrl() . $this->url()->fromRoute('user-register', array( 'action' => 'confirm-email-change-password', 'id' => $user->getRegistrationToken()));
                        $this->sendEmail(
                                $user->getEmail(),
                                $this->getTranslatorHelper()->translate('Please, confirm your request to change password!'),
                                sprintf($this->getTranslatorHelper()->translate('Hi, %s. Please, follow this link %s to confirm your request to change password.'), $user->getUsername(), $fullLink)
                        );
                        $entityManager->persist($user);
                        $entityManager->flush();
    
                        $viewModel = new ViewModel(array(
                            'email' => $user->getEmail(),
                            'navMenu' => $this->getOptions()->getNavMenu()
                        ));
    
                        $viewModel->setTemplate('csn-user/registration/password-change-success');
                        return $viewModel;
                    } catch (\Exception $e) {
                        return $this->getServiceLocator()->get('csnuser_error_view')->createErrorView(
                                $this->getTranslatorHelper()->translate('Something went wrong when trying to send activation email! Please, try again later.'),
                                $e,
                                $this->getOptions()->getDisplayExceptions(),
                                $this->getOptions()->getNavMenu()
                        );
                    }
                } else {
                    $message = 'The username or email is not valid!';
                }
            }
        }
    
        return new ViewModel(array('form' => $form, 'navMenu' => $this->getOptions()->getNavMenu(), 'message' => $message));
    }
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);
    }
861900
public function resetPassword()
    {
        $user = $this->_user;
        $user->password = $this->password;
        $user->removePasswordResetToken();

        return $user->save();
    }
326669
protected function resetPassword($user, $password)
    {
        $user->password = (new Hasher())->make($password);

        Person::save($user);
        auth()->login($user);
    }
695823
public function setPassword() {
		if (count($this->args) < 2) {
			$this->abort(__d('burzum/user_tools', 'You need to call this command with at least tow arguments.'));
		}

		$field = 'username';
		if (count($this->args) >= 3) {
			$field = $this->args[2];
		}

		$user = $this->UserTable->find()->where([$field => $this->args[0]])->first();
		$user->password = $this->UserTable->hashPassword($this->args[1]);
		if ($this->UserTable->save($user, ['validate' => false])) {
			$this->out('Password saved');
		}
	}
1290105
protected function reset()
    {
        $this->user = null;
        $this->lastAttempted = null;
        $this->viaRemember = false;
        $this->loggedOut = false;
        $this->tokenRetrievalAttempted = false;
        $this->recallAttempted  = false;
    }
459734
public function resetPassword()
    {
        // Retrieve received token
        $token = Input::get('token');

        // Validate token
        $resetToken = $this->resetPasswordRepository->getByUnexpiredToken($token);
        if (empty($resetToken)) {
            return view('nodes.api::reset-password.invalid');
        }

        // Retrieve received e-mail
        $email = Input::get('email');

        // Validate e-mail address
        if ($resetToken->email != $email) {
            return redirect()->back()->with(['email' => $email, 'error' => 'Token does not belong to e-mail address']);
        }

        // Retrieve passwords
        $password = Input::get('password');
        $repeatPassword = Input::get('repeat-password');

        // Validate passwords
        if ($password != $repeatPassword) {
            return redirect()->back()->with(['email' => $email, 'error' => 'The two passwords does not match each other']);
        }

        // All good! Update user's password
        $status = $this->resetPasswordRepository->updatePasswordByEmail($email, $password);
        if (empty($status)) {
            return redirect()->back()->with(['email' => $email, 'error' => 'Could not change user\'s password']);
        }

        // Mark token as used
        $resetToken->markAsUsed();

        return redirect()->route('nodes.api.auth.reset-password.done')->with('success', 'Password was successfully changed');
    }
149819
protected function resetPassword($user, $password)
    {
        $user->password = Hash::make($password);

        $user->setRememberToken(Str::random(60));

        $user->save();

        event(new PasswordReset($user));
    }
359194
def reset_password(app, appbuilder, username, password):
    
    _appbuilder = import_application(app, appbuilder)
    user = _appbuilder.sm.find_user(username=username)
    if not user:
        click.echo("User {0} not found.".format(username))
    else:
        _appbuilder.sm.reset_password(user.id, password)
        click.echo(click.style("User {0} reseted.".format(username), fg="green"))
1263416
@Restricted(NoExternalUse.class)
    @VisibleForTesting
    public final synchronized void reset() {
        // Wipe the data
        clear();
        
        // default values for the first time the config is created
        addMaskedPasswordParameterDefinition(hudson.model.PasswordParameterDefinition.class.getName());
        addMaskedPasswordParameterDefinition(com.michelin.cio.hudson.plugins.passwordparam.PasswordParameterDefinition.class.getName());
    }
233920
public function handleResetPassword()
    {
        if ($this->presenter->isAjax())
        {
            $allowedReset = (
                $this->presenter->user->isAllowed(UserAuthorizator::RES_RESET_PASSWORD_HANDLE)
                && $this->presenter->user->getId() !== $this->userEntity->getId()
                && (
                    !$this->userEntity->isInRole(UserAuthorizator::ROLE_ADMIN)
                    || $this->presenter->user->isAllowed(UserAuthorizator::RES_EDIT_ADMINS)
                )
            );

            if (!$allowedReset)
            {
                throw new ForbiddenRequestException;
            }

            try
            {
                $this->userManager->resetPassword($this->userEntity);

                $this->presenter->notificationAjax(
                    'Heslo resetováno',
                    'Heslo bylo úspěšně resetováno a uživateli byl odeslán e-mail.',
                    'success'
                );
            }
            catch (\Exception $exception)
            {
                throw $exception;
            }
        }
    }
1187694
@PostMapping(
      value = "/password/reset",
      headers = "Content-Type=application/x-www-form-urlencoded")
  @ResponseStatus(HttpStatus.NO_CONTENT)
  public void resetPassword(@Valid @ModelAttribute PasswordResetRequest passwordResetRequest) {
    accountService.resetPassword(passwordResetRequest.getEmail());
  }
754516
public function forgotPassword()
    {
        $sEmail = \OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter('lgn_usr');
        $this->_sForgotEmail = $sEmail;
        $oEmail = oxNew(\OxidEsales\Eshop\Core\Email::class);

        // problems sending passwd reminder ?
        $iSuccess = false;
        if ($sEmail) {
            $iSuccess = $oEmail->sendForgotPwdEmail($sEmail);
        }
        if ($iSuccess !== true) {
            $sError = ($iSuccess === false) ? 'ERROR_MESSAGE_PASSWORD_EMAIL_INVALID' : 'MESSAGE_NOT_ABLE_TO_SEND_EMAIL';
            \OxidEsales\Eshop\Core\Registry::getUtilsView()->addErrorToDisplay($sError, false, true);
            $this->_sForgotEmail = false;
        }
    }
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')
    )
1027404
public function resetPassword($password)
    {
        try {
            return (bool)$this->updateAttributes(['password_hash' => PasswordHelper::hash($password)]);
        } catch (Exception $e) {
            return false;
        }
    }
1156212
def allow_password_change?
        if params[:old_password]
          unless @user.authenticate(params[:old_password])
            raise ApplicationController::UNAUTHORIZED_ERROR 
          end
        else
          unless @token == @user.reset_token
            raise ApplicationController::UNAUTHORIZED_ERROR
          end
        end
        return true
      end