Generate reset password token and send it on e-mail.

@author Morten Rugaard <moru@nodes.dk>

@return \Nodes\Api\Http\Response
@throws \Nodes\Api\Auth\Exceptions\MissingUserModelException
@throws \Nodes\Exceptions\Exception
516490
public function generateResetToken()
    {
        // Retrieve data
        $email = $email = Input::get('email');

        // Validate that an API user model has been specified
        if (empty(config('nodes.api.auth.model'))) {
            throw new MissingUserModelException('No API auth model has been specified');
        }

        // Validate e-mail
        if (empty($email) || ! filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw (new Exception('Missing or invalid e-mail address', 412))->setStatusCode(412);
        }

        // Generate token and send e-mail
        $this->resetPasswordRepository->sendResetPasswordEmail(['email' => $email]);

        return $this->response->content([
            'email' => 'sent',
        ]);
    }
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));
    }
1140171
public function sendEmail()
    {
        $this->validate(request(), ['email' => 'required|email']);

        // Attempt to send the email.
        $this->forgotPassword->sendEmail(request('email'));

        return redirect(route('auth.password.sent'));
    }
861311
def send_reset_password_link(request):
    '''
    
    '''
    if not registration_settings.RESET_PASSWORD_VERIFICATION_ENABLED:
        raise Http404()
    serializer = SendResetPasswordLinkSerializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    login = serializer.validated_data['login']

    user = None
    for login_field in get_login_fields():
        user = get_user_by_lookup_dict(
            {login_field: login}, default=None, require_verified=False)
        if user:
            break

    if not user:
        raise UserNotFound()

    signer = ResetPasswordSigner({
        'user_id': user.pk,
    }, request=request)

    template_config = (
        registration_settings.RESET_PASSWORD_VERIFICATION_EMAIL_TEMPLATES)
    send_verification_notification(user, signer, template_config)

    return get_ok_response('Reset link sent')
76973
public function lostPasswordRequestAction() 
    {
        $pathAppConfigForm = '/meliscore/forms/meliscore_forgot';
        $melisMelisCoreConfig = $this->serviceLocator->get('MelisCoreConfig');
        $appConfigForm = $melisMelisCoreConfig->getItem($pathAppConfigForm);
        $translator = $this->getServiceLocator()->get('translator');
        
        $success = false;
        $errors  = array();
        $message = '';

        
        if($this->getRequest()->isPost())
        {
            $login = $this->getRequest()->getPost('usr_login');
            $email = $this->getRequest()->getPost('usr_email');
            
            $melisLostPass = $this->getServiceLocator()->get('MelisCoreLostPassword');
            $userTable = $this->getServiceLocator()->get('MelisCoreTableUser');
            $userData = $userTable->getDataByLoginAndEmail($login, $email);
            $userData = $userData->current();
            
            if($userData) 
            {
                if($melisLostPass->userExists($login))
                {
                    $success = $melisLostPass->addLostPassRequest($login, $email);
                    if($success)
                    {
                        $message = $translator->translate('tr_meliscore_email_lost_password_request_success');
                    }
                    else
                    {
                        $message = $translator->translate('tr_meliscore_email_lost_password_request_failed');
                    }
                }
                else
                {
                    $message = $translator->translate('tr_meliscore_email_lost_password_request_failed');
                }
            }
            else 
            {
                $success = false;
                $message = $translator->translate('tr_meliscore_email_failed');
            }
        }
        
        return new JsonModel(array('success' => $success, 'message' => $message));
    }
513076
public function sendResetLinkEmail(Request $request)
    {
        $this->validate($request, ['email' => 'required|email']);

        // We will send the password reset link to this user. Once we have attempted
        // to send the link, we will examine the response then see the message we
        // need to show to the user. Finally, we'll send out a proper response.
        $response = Password::broker()->sendResetLink($request->only('email'));

        switch ($response) {
            case Password::RESET_LINK_SENT:
                alert()->success('Success!',
                    'Please check your inbox for the email with instructions');

                $this->logLogin($request, 'password-forgot');

                return redirect(route('login'));

            default:
                return redirect()
                    ->back()
                    ->withInput($request->only('email'))
                    ->withErrors(['email' => trans($response)]);
        }
    }
483814
public function PasswordRequest() {
      Gdn::Locale()->SetTranslation('Email', T(UserModel::SigninLabelCode()));
      if ($this->Form->IsPostBack() === TRUE) {
         $this->Form->ValidateRule('Email', 'ValidateRequired');

         if ($this->Form->ErrorCount() == 0) {
            try {
               $Email = $this->Form->GetFormValue('Email');
               if (!$this->UserModel->PasswordRequest($Email)) {
                  $this->Form->SetValidationResults($this->UserModel->ValidationResults());
               }
            } catch (Exception $ex) {
               $this->Form->AddError($ex->getMessage());
            }
            if ($this->Form->ErrorCount() == 0) {
               $this->Form->AddError('Success!');
               $this->View = 'passwordrequestsent';
            }
         } else {
            if ($this->Form->ErrorCount() == 0)
               $this->Form->AddError("Couldn't find an account associated with that email/username.");
         }
      }
      $this->Render();
   }
828307
public function postForgot()
    {
        try
        {
            $email = Input::get('email');
            $this->passForm->forgot($email);
            return View::make(Config::get('cpanel::views.password_send'))
                ->with('email', $email);
        }
        catch (UserNotFoundException $e)
        {
            return Redirect::back()
                ->with('password_error', $e->getMessage());
        }
    }
564590
public function afterCreate()
    {
        $this->getDI()
            ->getMail()
            ->send([
                $this->user->email => $this->user->name
            ], "Reset your password", 'reset', [
                'resetUrl' => '/reset-password/' . $this->code . '/' . $this->user->email
            ]);
    }
968611
public function passwordAction()
    {
        $minLength = $this->container->getParameter('phlexible_user.password.min_length');

        $generator = new PasswordGenerator();
        $password = $generator->create($minLength, PasswordGenerator::TYPE_UNPRONOUNCABLE);

        return new JsonResponse(
            [
                'password' => $password,
                'success' => true,
            ]
        );
    }
937452
public function sendVerificationEmail(IlluminateModel $user)
    {
        if (empty($user)) {
            throw new ResetPasswordNoUserException('Could not find any user with those credentials');
        }

        // Generate email verification token
        $token = $this->generateEmailVerificationToken($user);

        // Generate email verification domain
        $domain = env('NODES_ENV', false) ? sprintf('https://%s.%s', env('APP_NAME'), env('APP_DOMAIN')) : config('app.url');

        // Send e-mail with instructions on how to reset password
        $status = (bool) Mail::send([
            'html' => config('nodes.api.email-verification.views.html', 'nodes.api::email-verification.emails.html'),
            'text' => config('nodes.api.email-verification.views.text', 'nodes.api::email-verification.emails.text'),
        ], [
            'user' => $user,
            'domain' => $domain,
            'email' => $user->email,
            'token' => $token,
            'expire' => config('nodes.api.email-verification.expire'),
            'senderName' => (config('nodes.api.email-verification.from.name') != 'Nodes') ? config('nodes.api.email-verification.from.name') : config('nodes.project.name'),
        ], function ($message) use ($user) {
            $message->to($user->email)
                ->from(config('nodes.api.email-verification.from.email', 'no-reply@nodes.dk'), config('nodes.api.email-verification.from.name', 'Nodes'))
                ->subject(config('nodes.api.email-verification.subject', 'Email verification request'));
        });

        return $status;
    }
691548
def gen_reset_password_token(self, user=None, send_email=None):
        
        if not user and "form" in current_context.data and request.method == "POST":
            form = current_context.data.form
            user = self.find_by_email(form[self.options["email_column"]].data)
            if user is None:
                if self.options["reset_password_token_error_message"]:
                    flash(self.options["reset_password_token_error_message"], "error")
                current_context.exit(trigger_action_group="reset_password_failed")
                
        if not user:
            raise InvalidOptionError("Invalid user in 'reset_password_token' action")

        token = self._gen_reset_password_token(user)
        self.reset_password_token_signal.send(self, user=user, token=token)
        if (send_email is None and self.options["send_reset_password_email"]) or send_email:
            to_email = getattr(user, self.options["email_column"])
            current_app.features.emails.send(to_email, "users/reset_password.txt", user=user, token=token)
        return token
1169536
public function resetPassword() : string {
		$newPass = bin2hex(random_bytes(20));
		$newHash = password_hash($newPass, PASSWORD_BCRYPT);

		$stmt = $this->db->prepare(
			"UPDATE accounts SET pw_hash=? WHERE id=?;"
		);
		$stmt->bind_param("si", $newHash, $this->id);
		$stmt->execute();
		$this->db->commit();
		$this->pwHash = $newHash;

		$this->sessionManager->wipeLoginSession();
		return $newPass;
	}
1088768
public function resetAction(Request $request, PasswordResetToken $token): Response
    {
        $user = $this->userRepositoryCollection->findUserByToken($token);

        if ($user === null) {
            return new RedirectResponse(
                $this->router->generate('multi_user_login')
            );
        }

        $changePasswordTransferObject = ChangePasswordDataTransferObject::forUser($user);
        $form = $this->formFactory->create(ChangePasswordType::class, $changePasswordTransferObject);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->resetPasswordHandler->handle($form->getData());

            $this->flashBag->add(
                'success',
                $this->translator->trans(
                    'sumocoders.multiuserbundle.flash.password_reset_success'
                )
            );

            return new RedirectResponse(
                $this->router->generate('multi_user_login')
            );
        }

        return $this->templating->renderResponse(
            'SumoCodersFrameworkMultiUserBundle:PasswordReset:reset.html.twig',
            [
                'form' => $form->createView(),
            ]
        );
    }
182024
public function passwordForgot()
    {
        //Checks if reset password is enabled
        if (!getConfig('users.reset_password')) {
            $this->Flash->error(I18N_DISABLED);

            return $this->redirect(['_name' => 'homepage']);
        }

        $entity = $this->Users->newEntity($this->request->getData(), ['validate' => 'DoNotRequirePresence']);

        if ($this->request->is('post')) {
            //Checks for reCAPTCHA, if requested
            if (!getConfig('security.recaptcha') || $this->Recaptcha->verify()) {
                $user = $this->Users->findActiveByEmail($this->request->getData('email'))->first();

                if ($user) {
                    $token = $this->Token->create($user->email, ['type' => 'password_forgot', 'user_id' => $user->id]);
                    $this->getMailer('MeCms.User')
                        ->set('url', Router::url(['_name' => 'passwordReset', $user->id, $token], true))
                        ->send('passwordForgot', [$user]);
                    $this->Flash->success(__d('me_cms', 'We have sent you an email to reset your password'));

                    return $this->redirect(['_name' => 'login']);
                }

                if ($this->request->getData('email')) {
                    Log::error(sprintf(
                        '%s - Forgot password request with invalid email `%s`',
                        $this->request->clientIp(),
                        $this->request->getData('email')
                    ), 'users');
                }

                $this->Flash->error(__d('me_cms', 'No account found'));
            } else {
                $this->Flash->error(__d('me_cms', 'You must fill in the {0} control correctly', 'reCAPTCHA'));
            }
        }

        $this->set('user', $entity);
        $this->viewBuilder()->setLayout('login');
    }
434559
public function sendEmail()
    {
        /* @var $user User */
        $user = User::findOne([
            'status' => User::STATUS_ACTIVE,
            'email' => $this->email,
        ]);

        if ($user) {
            if (!User::isPasswordResetTokenValid($user->password_reset_token)) {
                $user->generatePasswordResetToken();
            }

            if ($user->save()) {
                $resetUrl = $this->resetUrl;
                $resetUrl['token'] = $user->password_reset_token;
                return Yii::$app->mailer->compose($this->mailView, ['user' => $user, 'resetUrl' => $resetUrl])
                    ->setTo($this->email)
                    ->setSubject(Yii::t('maddoger/user', 'Password reset for {app}', ['app' => \Yii::$app->name]))
                    ->send();
            }
        }

        return false;
    }
983522
public function sendResetLinkEmail(Request $request)
    {
        $this->validate($request, ['email' => 'required|email']);

        // We will send the password reset link to this user. Once we have attempted
        // to send the link, we will examine the response then see the message we
        // need to show to the user. Finally, we'll send out a proper response.
        $response = $this->broker()->sendResetLink(
            $request->only('email')
        );

        switch ($response) {
            case Password::RESET_LINK_SENT:
                return response()->json([
                    'success' => true
                ]);

            case Password::INVALID_USER:
            default:
                return response()->json([
                    'success' => false,
                    'message' => 'Invalid user'
                ]);
        }
    }