Forget check.

@Route("/forgot_check", name="amulen_forgot_check")
@Method("POST")
@Template("FlowcodeUserBundle:Security:forgot.html.twig")
160119
public function forgotCheckAction(Request $request)
    {
        $error = null;
        $last_email = null;

        $userService = $this->get("flowcode.user");
        $user = $userService->loadUserByUsername($request->get("_username"));

        if ($user) {
            $userService->resetPasssword($user);
        } else {
            $error = array(
                "messageKey" => "security.login.unknown_user",
                "messageData" => array(),
            );
        }


        return array(
            "error" => $error,
            "last_email" => $last_email,
        );
    }
1273328
public function actionCheckRoute()
    {
        $post = Yii::$app->request->post();
        if (empty($post['route'])) {
            $result = Yii::t($this->tcModule, 'Error in POST-ed data');
        } else {
            $ctrlLinkPrefix = empty($post['ctrlLinkPrefix']) ? null : $post['ctrlLinkPrefix'];

            $url = ContentMenuBuilder::routeToLink($post['route'], $ctrlLinkPrefix);

            if (Yii::$app instanceof UniApplication && Yii::$app->type == UniApplication::APP_TYPE_BACKEND) {
                // backend application don't have frontend-routes, $url is wrong
                $url = false;

                // if module-container (system-module) has ApplicationModel - it can get frontend application with correct routes
                $containerModule = $this->module->module;
                if ($containerModule instanceof UniModule && array_key_exists(static::$sysAppModel, $containerModule->models)) {
                    $appModel = $containerModule::model(static::$sysAppModel);
                    $appFront = $appModel::initFrontendApplication();
                    $url = ContentMenuBuilder::routeToLink($post['route'], $ctrlLinkPrefix);
                    $appModel::restoreApplication();
                }
            }

            if ($url) {
                $result = htmlspecialchars($url);
            } else {
                $result = Yii::t($this->tcModule, "Can't resolve route '{route}'", ['route' => $post['route']]);
                if (!empty(ContentMenuBuilder::$errorRouteConvert)) {
                    $result .= ', ERROR: ' . ContentMenuBuilder::$errorRouteConvert;
                }
            }
        }
        return $result;
    }
395939
async def forget(request):
    
    auth_policy = request.get(POLICY_KEY)
    if auth_policy is None:
        raise RuntimeError('auth_middleware not installed')

    return await auth_policy.forget(request)
42347
protected function _handleUnauthenticatedAccess()
    {
        header("HTTP/1.0 401 Unauthorized");
        $renderer = new TwigRenderer();
        $output = $renderer->render('unauth.tmpl', array());
        $result = array("code"=>"401","message" => $output);
        echo parent::encodeData($result);
        exit;

    }
384228
public function forgotPassword(Request $request)
    {
        $form = $this->app->form(new PhraseaForgotPasswordForm());
        $service = $this->getRecoveryService();

        try {
            if ('POST' === $request->getMethod()) {
                $form->handleRequest($request);

                if ($form->isValid()) {
                    $data = $form->getData();

                    try {
                        $service->requestPasswordResetToken($data['email'], true);
                    }
                    catch (InvalidArgumentException $ex) {
                        /** @Ignore */
                        $message = $this->app->trans($ex->getMessage());
                        throw new FormProcessingException($message, 0, $ex);
                    }

                    $this->app->addFlash('info', $this->app->trans('phraseanet:: Un email vient de vous etre envoye'));

                    return $this->app->redirectPath('login_forgot_password');
                }
            }
        } catch (FormProcessingException $e) {
            $this->app->addFlash('error', $e->getMessage());
        }

        return $this->render('login/forgot-password.html.twig', array_merge(
            $this->getDefaultTemplateVariables($request),
            [ 'form'  => $form->createView() ]
        ));
    }
1329554
public function reset()
    {
        // Lookup token
        $token = $this->get('request_stack')->getCurrentRequest()->get('token');
        if(!$token) {
            return $this->render('FOMUserBundle:Login:error-notoken.html.twig');
        }

        $user = $this->getDoctrine()->getRepository("FOMUserBundle:User")->findOneByRegistrationToken($token);
        if(!$user) {
            //@TODO: Get site email from configuration
            return $this->render('FOMUserBundle:Login:error-notoken.html.twig', array(
                'site_email' => 'FOFO'));
        }

        $user->setRegistrationToken(hash("sha1",rand()));
        $user->setRegistrationTime(new \DateTime());

        $this->sendEmail($user);

        $em = $this->getDoctrine()->getManager();
        $em->persist($user);
        $em->flush();

        return $this->redirect($this->generateUrl('fom_user_registration_send'));
    }
1171019
function (form) {
              if (config.web.multiTenancy.enabled && req.organization) {
                setAccountStoreByHref(form.data, req.organization);
              } else {
                /**
                 * Delete this form field, it's automatically added by the
                 * forms library.  If we don't delete it, we submit a null
                 * name key to the REST API and we get an error.
                 */
                delete form.data.organizationNameKey;
              }

              helpers.authenticate(form.data, req, res, function (err) {
                if (err) {
                  if (err.code === 2014) {
                    err.message = err.userMessage = 'Invalid Username, Password, or Organization';
                  }

                  err = oktaErrorTransformer(err);

                  return renderForm(form, { error: err.userMessage || err.message });
                }

                helpers.loginResponder(req, res);
              });
            }
485316
protected function ForgotPasswordConfirm()
	{
		if (!$this->_login->getCanRetrievePassword())
		{
			$this->FormLogin();
			return;
		}
		$myWords = $this->WordCollection();

		$container = new XmlnukeUIAlert($this->_context, UIAlert::BoxInfo);
		$container->setAutoHide(5000);
		$this->_blockCenter->addXmlnukeObject($container);

		$user = $this->_users->getUserEMail( $this->_context->get("email") );

		if (is_null($user))
		{
			$container->addXmlnukeObject(new XmlnukeText($myWords->Value("FORGOTUSERFAIL"), true));
			$this->ForgotPassword();
		}
		else
		{
			$newpassword = sha1($this->getRandomPassword());
			$user->setField('TOKEN_PWD_RESET', $newpassword);
			$user->setField('TOKEN_PWD_RESET_VALID', DateUtil::DateAdd(DateUtil::Today(DATEFORMAT::YMD), 2, DATEFORMAT::YMD));
			$this->_users->Save();
			$this->sendResetPasswordMessage($myWords, $user->getField($this->_users->getUserTable()->name), $user->getField($this->_users->getUserTable()->username), $user->getField($this->_users->getUserTable()->email), $newpassword );
			$container->addXmlnukeObject(new XmlnukeText($myWords->Value("FORGOTUSEROK"), true));
			$this->FormLogin();
		}
	}
861655
public function checkEmailAction(Request $request)
    {
        $email = $request->query->get('email');

        if (empty($email)) {
            // the user does not come from the sendEmail action
            return new RedirectResponse($this->generateUrl('fos_user_resetting_request'));
        }

        return $this->render('FOSUserBundle:Resetting:checkEmail.html.twig', array(
            'email' => $email,
        ));
    }
628972
public function checkErrorsBeforePost($fid, $tid, $qid, $pid, $page, $errors)
    {
        $lang_antispam_questions = require ForumEnv::get('FORUM_ROOT').'lang/'.User::get()->language.'/antispam.php';

        $fid = Container::get('hooks')->fire('model.post.check_errors_before_post_start', $fid);

        // Antispam feature
        if (User::get()->is_guest) {
            // It's a guest, so we have to validate the username
            $profile = new \RunBB\Model\Profile();
            $errors = $profile->checkUsername(Utils::trim(Input::post('req_username')), $errors);

            $errors = Container::get('hooks')->fire('model.post.check_errors_before_post_antispam', $errors);

            $question = Input::post('captcha_q') ? trim(Input::post('captcha_q')) : '';
            $answer = Input::post('captcha') ? strtoupper(trim(Input::post('captcha'))) : '';
            $lang_antispam_questions_array = [];

            foreach ($lang_antispam_questions as $k => $v) {
                $lang_antispam_questions_array[md5($k)] = strtoupper($v);
            }

            if (empty($lang_antispam_questions_array[$question]) ||
                $lang_antispam_questions_array[$question] != $answer) {
                $errors[] = __('Robot test fail');
            }
        }

        // Flood protection
        if (Input::post('preview') != '' &&
            User::get()->last_post != '' &&
            (time() - User::get()->last_post) < Container::get('prefs')->get(User::get(), 'post.min_interval')) {
            $errors[] = sprintf(
                __('Flood start'),
                Container::get('prefs')->get(User::get(), 'post.min_interval'),
                Container::get('prefs')->get(User::get(), 'post.min_interval') - (time() - User::get()->last_post)
            );
        }

        // If it's a new topic
        if ($fid) {
            $subject = Utils::trim(Input::post('req_subject'));
            $subject = Container::get('hooks')->fire('model.post.check_errors_before_new_topic_subject', $subject);

            if (ForumSettings::get('o_censoring') == '1') {
                $censored_subject = Utils::trim(Utils::censor($subject));
                $censored_subject = Container::get('hooks')
                    ->fire('model.post.check_errors_before_censored', $censored_subject);
            }

            if ($subject == '') {
                $errors[] = __('No subject');
            } elseif (ForumSettings::get('o_censoring') == '1' && $censored_subject == '') {
                $errors[] = __('No subject after censoring');
            } elseif (Utils::strlen($subject) > 70) {
                $errors[] = __('Too long subject');
            } elseif (ForumSettings::get('p_subject_all_caps') == '0' &&
                Utils::isAllUppercase($subject) && !User::get()->is_admmod) {
                $errors[] = __('All caps subject');
            }

            $errors = Container::get('hooks')->fire('model.post.check_errors_before_new_topic_errors', $errors);
        }

        if (User::get()->is_guest) {
            $email = strtolower(Utils::trim((ForumSettings::get('p_force_guest_email') == '1') ?
                Input::post('req_email') : Input::post('email')));

            if (ForumSettings::get('p_force_guest_email') == '1' || $email != '') {
                $errors = Container::get('hooks')->fire('model.post.check_errors_before_post_email', $errors, $email);

                if (!Container::get('email')->isValidEmail($email)) {
                    $errors[] = __('Invalid email');
                }

                // Check if it's a banned email address
                // we should only check guests because members' addresses are already verified
                if (User::get()->is_guest && Container::get('email')->isBannedEmail($email)) {
                    if (ForumSettings::get('p_allow_banned_email') == '0') {
                        $errors[] = __('Banned email');
                    }

                    $errors['banned_email'] = 1; // Used later when we send an alert email
                }
            }
        }

        // Clean up message from POST
        $message = Utils::linebreaks(Utils::trim(Input::post('req_message')));
        $message = Container::get('hooks')->fire('model.post.check_errors_before_post_message', $message);

        // Here we use strlen() not Utils::strlen() as we want to limit the post to
        // FEATHER_MAX_POSTSIZE bytes, not characters
        if (strlen($message) > ForumEnv::get('FEATHER_MAX_POSTSIZE')) {
            $errors[] = sprintf(
                __('Too long message'),
                Utils::numberFormat(ForumEnv::get('FEATHER_MAX_POSTSIZE'))
            );
        } elseif (ForumSettings::get('p_message_all_caps') == '0' &&
            Utils::isAllUppercase($message) && !User::get()->is_admmod) {
            $errors[] = __('All caps message');
        }

        // Validate BBCode syntax
        if (ForumSettings::get('p_message_bbcode') == '1') {
            $message = Container::get('parser')->parseForSave($message, $errors);
            $message = Container::get('hooks')->fire('model.post.check_errors_before_post_bbcode', $message);
        }

        if (empty($errors)) {
            $errors = Container::get('hooks')->fire('model.post.check_errors_before_post_no_error', $errors);
            if ($message == '') {
                $errors[] = __('No message');
            } elseif (ForumSettings::get('o_censoring') == '1') {
                // Censor message to see if that causes problems
                $censored_message = Utils::trim(Utils::censor($message));

                if ($censored_message == '') {
                    $errors[] = __('No message after censoring');
                }
            }
        }

        $errors = Container::get('hooks')->fire('model.post.check_errors_before_post', $errors);

        return $errors;
    }
934337
function() {
			if ( $.fn.resetForm ) {
				$(this.currentForm).resetForm();
			}
			this.submitted = {};
			this.lastElement = null;
			this.prepareForm();
			this.hideErrors();
			this.elements().removeClass( this.settings.errorClass ).removeData( "previousValue" );
		}
189601
public function index_onDelete()
    {
        if (method_exists($this->controller, 'onDelete')) {
            return call_user_func_array([$this->controller, 'onDelete'], func_get_args());
        }

        /*
         * Validate checked identifiers
         */
        $checkedIds = post('checked');

        if (!$checkedIds || !is_array($checkedIds) || !count($checkedIds)) {
            Flash::error(Lang::get('backend::lang.list.delete_selected_empty'));
            return $this->controller->listRefresh();
        }

        /*
         * Establish the list definition
         */
        $definition = post('definition', $this->primaryDefinition);

        if (!isset($this->listDefinitions[$definition])) {
            throw new ApplicationException(Lang::get('backend::lang.list.missing_parent_definition', compact('definition')));
        }

        $listConfig = $this->controller->listGetConfig($definition);

        /*
         * Create the model
         */
        $class = $listConfig->modelClass;
        $model = new $class;
        $model = $this->controller->listExtendModel($model, $definition);

        /*
         * Create the query
         */
        $query = $model->newQuery();
        $this->controller->listExtendQueryBefore($query, $definition);

        $query->whereIn($model->getKeyName(), $checkedIds);
        $this->controller->listExtendQuery($query, $definition);

        /*
         * Delete records
         */
        $records = $query->get();

        if ($records->count()) {
            foreach ($records as $record) {
                $record->delete();
            }

            Flash::success(Lang::get('backend::lang.list.delete_selected_success'));
        }
        else {
            Flash::error(Lang::get('backend::lang.list.delete_selected_empty'));
        }

        return $this->controller->listRefresh($definition);
    }
1274931
public function resetPasswordAction() 
    {
        $pathAppConfigForm = '/meliscore/forms/meliscore_resetpass';
        $melisMelisCoreConfig = $this->serviceLocator->get('MelisCoreConfig');
        $appConfigForm = $melisMelisCoreConfig->getItem($pathAppConfigForm);
        $translator = $this->getServiceLocator()->get('translator');

        $rhash = $this->getHash();
        $melisLostPass = $this->getServiceLocator()->get('MelisCoreLostPassword');
        $hashExists = false;
        $textMessage = '';
        $success = 0;
        $login = '';
        $data = array();
        if($melisLostPass->hashExists($rhash)) {
            $hashExists = true;
            $data = $melisLostPass->getPasswordRequestData($rhash);
            foreach($data as $val) {
                $login = $val->rh_login;
            }
        }


        $factory = new \Zend\Form\Factory();
        $forgotForm = $factory->createForm($appConfigForm);
        
        $translator = $this->getServiceLocator()->get('translator');
        $this->getServiceLocator()->get('ViewHelperManager')->get('HeadTitle')->set($translator->translate('tr_meliscore_reset_password_header') . ' - ');
        
        $view = new ViewModel();
        if($this->getRequest()->isPost())
        {
            
            $password = $this->getRequest()->getPost('usr_pass');
            $confirmPass = $this->getRequest()->getPost('usr_pass_confirm');
            $passValidator = new \MelisCore\Validator\MelisPasswordValidator();
            
                if(strlen($password) >= 8) {
                    if(strlen($confirmPass) >= 8) {
                        //$passValidator = new \Zend\Validator\Regex(array('pattern' => '/^(?=.*?[0-9])(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[^\w\s]).{8,}$/'));
                        $passValidator = new \MelisCore\Validator\MelisPasswordValidator();
                        if($passValidator->isValid($password))
                        {
                            // password and confirm password matching
                            if($password == $confirmPass)
                            {
                                $melisLostPass->processUpdatePassword($rhash, $password);
                                $textMessage = "tr_meliscore_user_password_change_succes";
                                $success = 1;
                                header( "location:/melis/login");
                            }
                            else
                            {
                                $success = 0;
                                $textMessage = 'tr_meliscore_tool_user_usr_password_not_match';
                            } // password and confirm password matching
                        }
                        else {
                                $success = 0;
                                $textMessage = 'tr_meliscore_tool_user_usr_password_regex_not_match';
                        } // password regex validator
                    }
                    else {
                        $success = 0;
                        $textMessage = 'tr_meliscore_tool_user_usr_confirm_password_error_low';
                    }// end confirm password length
                }
                else {
                    $success = 0;
                    $textMessage = 'tr_meliscore_tool_user_usr_password_error_low';
                }// end password length
        }
        
        
        $view->setVariable('meliscore_resetpass', $forgotForm);
        $view->setVariable('formFactory', $factory);
        $view->setVariable('formConfig', $appConfigForm);
        $view->hashExists = $hashExists;
        $view->message = $translator->translate($textMessage);
        $view->success = $success;
        $view->rhash =  $rhash;
        $this->layout()->schemes = $this->getSchemes();

        return $view;
    }
1343474
private function managePost()
    {
        // Do only react on POST requests
        if ($_SERVER['REQUEST_METHOD'] != 'POST' || empty($_POST)) {
            return;
        }

        /* @var $post \Core\Http\Post\Post */
        $this->di->mapService('core.http.post', '\Core\Http\Post\Post');

        $post = $this->di->get('core.http.post');

        // Setting the name of the session token that has to/gets sent with a form
        $post->setTokenName($this->config->get('Core', 'security.form.token'));

        // Validate posted token with session token
        if (!$post->validateCompareWithPostToken($this->di->get('core.security.form.token'))) {
            return;
        }

        // Some data cleanup
        $post->trimData();

        // Assingn app related post data to the corresponding app
        $post_data = $post->get();

        foreach ($post_data as $name => $data) {
            $app = $this->getAppInstance($name);
            $app->post->set($data);
        }
    }
1224193
public function postRequest(Request $request)
    {
        // Validate the form data
        $result = $this->validate($request, [
            'email' => 'required|email|max:255'
        ]);

        // Fetch the user in question
        $user = Sentinel::findUserByCredentials(['email' => $request->get('email')]);

        // Only send them an email if they have a valid, inactive account
        if ($user) {
            // Generate a new code
            $reminder = Reminder::create($user);

            // Send the email
            $code = $reminder->code;
            $email = $user->email;
            Mail::to($email)->queue(new CentaurPasswordReset($code));
        }

        $message = 'Instructions for changing your password will be sent to your email address if it is associated with a valid account.';

        if ($request->expectsJson()) {
            return response()->json(['message' => $message, 'code' => $code], 200);
        }

        Session::flash('success', $message);
        return redirect()->route('dashboard');
    }
290259
public function clearCache()
    {
        static::$cache = [];

        // remove our "remembered" submitted value
        $this->submitted = null;

        // remove our "remembered" valid value
        foreach ($this->fields as $field) {
            if ($field instanceof AbstractFormField) {
                $field->clearCache();
            }
        }
        return $this;
    }
1350581
public function postIndex()
    {
        $oInput     = Factory::service('Input');
        $oHttpCodes = Factory::service('HttpCodes');

        if (!userHasPermission('admin:cdn:manager:bucket:create')) {
            throw new ApiException(
                'You do not have permission to create this resource',
                $oHttpCodes::STATUS_UNAUTHORIZED
            );
        }

        //  @todo (Pablo - 2018-08-16) - Remove once CrudController validates properly itself
        if (!$oInput->post('label')) {
            throw new ApiException(
                '`label` is a required field',
                $oHttpCodes::STATUS_UNAUTHORIZED
            );
        }

        return parent::postIndex();
    }