Register bindings for the password reset

@author Steve Montambeault
@link   http://stevemo.ca
355423
public function registerPassword()
    {
        $app = $this->app;

        $app->bind('Stevemo\Cpanel\User\Form\PasswordFormInterface', function($app)
        {
           return new PasswordForm(
               new PasswordValidator($app['validator'], new MessageBag),
               $app->make('Stevemo\Cpanel\User\Repo\CpanelUserInterface'),
               $app->make('Stevemo\Cpanel\User\UserMailerInterface')
           );
        });

        $app->bind('Stevemo\Cpanel\User\UserMailerInterface', function($app)
        {
            return new UserMailer();
        });
    }
993509
protected function registerResetCommand(): void
    {
        $this->app->singleton('orchestra.commands.tenanti.reset', function (Application $app) {
            return new ResetCommand($app->make('orchestra.tenanti'));
        });
    }
1157143
public function password()
    {
        $this->setData('formTitle', __("Change password"));
        if ($this->getServiceLocator()->get(ApplicationService::SERVICE_ID)->isDemo()) {
            $this->setData('myForm', __('Unable to change passwords in demo mode'));
        } else {
            $myFormContainer = new tao_actions_form_UserPassword();
            $myForm = $myFormContainer->getForm();
            if($myForm->isSubmited()){
                if($myForm->isValid()){
                    $user = $this->getUserService()->getCurrentUser();
                    $this->getServiceLocator()->get(tao_models_classes_UserService::SERVICE_ID)
                        ->setPassword($user, $myForm->getValue('newpassword'));
                    $this->setData('message', __('Password changed'));
                }
            }
            $this->setData('myForm', $myForm->render());
        }

        $this->setView('form/settings_user.tpl');
    }
435843
def register(self, password):
        """"""

        if len(password) < 8:
            raise ValueError("Password must be at least 8 characters.")

        params = {"name": self.nick, "password": password}
        resp = self.conn.make_api_call("register", params)

        if "error" in resp:
            raise RuntimeError(f"{resp['error'].get('message') or resp['error']}")

        self.conn.make_call("useSession", resp["session"])
        self.conn.cookies.update({"session": resp["session"]})
        self.logged_in = True
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')
    )
652074
public function signUp()
  {
    if (isset($_POST['signUp'])) {
      // Сheck for occupancy
      if ($_POST['name'] == '' || $_POST['email'] == '' || $_POST['password'] == '' || $_POST['confirmPassword'] == '') {
        $this->errors[] = 'Fill in all the fields';
      } 

      // Check for existence username
      if (R::count('users', 'name = ?', array($_POST['name'])) > 0) {
        $this->errors[] = 'A user with this name already exists';
      } 

      // Check for existence email in table
      if (R::count('users', 'email = ?', array($_POST['email'])) > 0) {
        $this->errors[] = 'This account is already taken! Please Login';
      }

       // Check for password math
      if ($_POST['password'] != $_POST['confirmPassword']) {
        $this->errors[] = 'The passwords you entered do not match!';
      }

      // Set min symbols 8 on the password
      if (strlen($_POST['password']) < 8) {
        $this->errors[] = 'The password must contain at least 8 characters!';
      }

      // If All ok
      if (empty($this->errors)) {
        $createUser = R::dispense('users');
        $createUser->name = strip_tags($_POST['name']);
        $createUser->email = strip_tags($_POST['email']);
        $createUser->password = password_hash(strip_tags($_POST['password']), PASSWORD_DEFAULT);
        R::store($createUser);

        redirect('/login');
      } else {
        echo "<div class='alert alert-danger' role='alert'>" . array_shift($this->errors) . "</div>";
      }
    }
  }
739833
function onConfirmPasswordReset() {
  var code = $('#password-reset-code').val();
  var password = $('#password-reset-password').val();
  auth.confirmPasswordReset(code, password).then(function() {
    alertSuccess('Password has been changed!');
  }, onAuthError);
}
707443
def reset_password(self, user, password):
        
        user.password = password
        self.user_manager.save(user)
        if app.config.SECURITY_SEND_PASSWORD_RESET_NOTICE_EMAIL:
            self.send_mail(
                _('flask_unchained.bundles.security:email_subject.password_reset_notice'),
                to=user.email,
                template='security/email/password_reset_notice.html',
                user=user)
        password_reset.send(app._get_current_object(), user=user)
541772
public function editUserRegister()
    {
        $this->controlAccessUserRegister();
        $this->setTitleEditUserRegister();
        $this->setBreadcrumbEditUserRegister();

        $this->submitUserRegister();
        $this->setData('password_limit', $this->user->getPasswordLength());
        $this->outputEditUserRegister();
    }
496780
protected function registerBindings()
    {
        $binding = config('binding')?: [];

        foreach($binding as $contract => $implementation) {
            $this->bind($contract, $implementation);
        }
    }
1340630
def reset_password
    email = params[:session] && params[:session][:email]
    credential = Credentials::Email.with email

    if user = (credential && credential.user)
      token = Tokens::PasswordReset.random_for user
      email = ::SessionMailer.reset_password_email(email, token, root_url)
      # TODO(pwnall): fix the serialization errors blocking deliver_later
      email.deliver_now
    end

    respond_to do |format|
      if user
        format.html do
          redirect_to new_session_url, alert:
              'Please check your e-mail for instructions'
        end
        format.json { render json: { } }
      else
        error_text = 'Invalid e-mail'
        format.html do
          redirect_to new_session_url, alert: error_text
        end
        format.json do
          render json: { error: :not_found, text: notice }
        end
      end
    end
  end
871754
def forgot_password_view(self):
        """"""

        # Initialize form
        form = self.ForgotPasswordFormClass(request.form)

        # Process valid POST
        if request.method == 'POST' and form.validate():
            # Get User and UserEmail by email
            email = form.email.data
            user, user_email = self.db_manager.get_user_and_user_email_by_email(email)

            if user and user_email:
                # Send reset_password email
                self.email_manager.send_reset_password_email(user, user_email)

                # Send forgot_password signal
                signals.user_forgot_password.send(current_app._get_current_object(), user=user)

            # Flash a system message
            flash(_(
                "A reset password email has been sent to '%(email)s'. Open that email and follow the instructions to reset your password.",
                email=email), 'success')

            # Redirect to the login page
            return redirect(self._endpoint_url(self.USER_AFTER_FORGOT_PASSWORD_ENDPOINT))

        # Render form
        self.prepare_domain_translations()
        return render_template(self.USER_FORGOT_PASSWORD_TEMPLATE, form=form)
39675
public function registerValidators()
    {
        Validator::extend('oldPassword', function ($attribute, $value, $parameters) {

            $checkOldPassword = Auth::attempt(['id' => Auth::user()->id, 'password' => $value]);

            if (!$checkOldPassword) {
                return false;
            }

            return true;

        }, 'The old password is incorrect.');
    }
1219253
def reset_password(self):
        '''
        
        '''
        post_data = self.get_post_data()

        if 'email' in post_data:
            userinfo = MUser.get_by_email(post_data['email'])

            if tools.timestamp() - userinfo.time_reset_passwd < 70:
                self.set_status(400)
                kwd = {
                    'info': '两次重置密码时间应该大于1分钟',
                    'link': '/user/reset-password',
                }
                self.render('misc/html/404.html', kwd=kwd, userinfo=self.userinfo)
                return False

            if userinfo:
                timestamp = tools.timestamp()
                passwd = userinfo.user_pass
                username = userinfo.user_name
                hash_str = tools.md5(username + str(timestamp) + passwd)
                url_reset = '{0}/user/reset-passwd?u={1}&t={2}&p={3}'.format(
                    config.SITE_CFG['site_url'],
                    username,
                    timestamp,
                    hash_str)
                email_cnt = '''<div>请查看下面的信息，并<span style="color:red">谨慎操作</span>：</div>
            <div>您在"{0}"网站（{1}）申请了密码重置，如果确定要进行密码重置，请打开下面链接：</div>
            <div><a href={2}>{2}</a></div>
            <div>如果无法确定本信息的有效性，请忽略本邮件。</div>'''.format(config.SMTP_CFG['name'],
                                                       config.SITE_CFG['site_url'],
                                                       url_reset)

                if send_mail([userinfo.user_email], "{0}|密码重置".format(config.SMTP_CFG['name']),
                             email_cnt):
                    MUser.update_time_reset_passwd(username, timestamp)
                    self.set_status(200)
                    logger.info('password has been reset.')
                    return True

                self.set_status(400)
                return False
            self.set_status(400)
            return False
        self.set_status(400)
        return False
1070336
public function initialize()
    {
        $this->hasMany('id', UserPasswordChange::class, 'user_id', [
            'alias' => 'PasswordChanges',
            'foreignKey' => [
                'action' => Relation::ACTION_CASCADE,
            ],
        ]);

        $this->hasMany('id', UserPasswordReset::class, 'user_id', [
            'alias' => 'PasswordResets',
            'foreignKey' => [
                'action' => Relation::ACTION_CASCADE,
            ],
        ]);

        $this->hasMany('id', UserLoginHistory::class, 'user_id', [
            'alias' => 'LoginHistory',
            'foreignKey' => [
                'action' => Relation::ACTION_CASCADE,
            ],
        ]);

        $this->belongsTo("user_type_id", UserType::class, "id", [
            "alias" => "UserType",
            "foreignKey" => [
                "allowNulls" => true,
                "message" => "The user type specified is invalid!"
            ],
        ]);
    }
436329
public function resetPassword()
    {
        $user = $this->_user;
        $user->setPassword($this->password);
        $user->removePasswordResetToken();
        Event::off(BaseActiveRecord::className(), BaseActiveRecord::EVENT_AFTER_UPDATE);

        return $user->save(false);
    }
542200
async def set_password(self, password):
        
        await self.controller.change_user_password(self.username, password)
        self._user_info.password = password