prepare csrf token protection if $this->protect_form_forgery is true

@return void
977534
protected function protectFromForgery()
    {
        if(property_exists($this, 'protect_from_forgery') && $this->protect_from_forgery === true){

            $request = $this->app->make('http.request');
            if ($request->isPost() || $request->isPut()) {

                if(property_exists($this, 'forgery_throw_exception') && $this->protect_throw_exception === false){
                    try{
                        $this->app->make('security.csrf')->run();
                    }catch (CsrfTokenMatchException $csrf){
                        //
                    }
                }else{
                    $this->app->make('security.csrf')->run();
                }
            }

        }
    }
1103575
private function validateToken(string $formName, string $token): bool
    {
        $sortedCsrf = $this->getStoredCsrfToken($formName);
        if (!is_null($sortedCsrf)) {
            $csrfData = Session::getInstance()->read('__CSRF_TOKEN', []);
            if (is_null($this->request->getHeader('CSRF_KEEP_ALIVE'))
                && is_null($this->request->getParameter('CSRF_KEEP_ALIVE'))) {
                $csrfData[$formName] = '';
                Session::getInstance()->set('__CSRF_TOKEN', $csrfData);
            }
            return hash_equals($sortedCsrf, $token);
        }
        return false;
    }
48460
public function buildFormFactory()
    {
        $this->ensureCsrfTokenManagerAndTranslatorExist();
        $validator = $this->buildValidator();
        $csrf      = new CsrfExtension(
            $this->csrf_token_manager,
            $this->translator,
            TranslatorBuilder::TRANSLATION_DOMAIN
        );
        $builder   = Forms::createFormFactoryBuilder()->addExtension($csrf)
                                            ->addExtension(new ValidatorExtension($validator))
                                            ->addExtension(new HttpFoundationExtension());
        foreach ($this->form_extensions as $extension) {
            $builder->addExtension($extension);
        }
        return $builder->getFormFactory();
    }
1369233
def confirm_register_form_factory(Form):
    """"""
    class CsrfDisabledProfileForm(ProfileForm):
        """Subclass of ProfileForm to disable CSRF token in the inner form.

        This class will always be a inner form field of the parent class
        `Form`. The parent will add/remove the CSRF token in the form.
        """

        def __init__(self, *args, **kwargs):
            """Initialize the object by hardcoding CSRF token to false."""
            kwargs = _update_with_csrf_disabled(kwargs)
            super(CsrfDisabledProfileForm, self).__init__(*args, **kwargs)

    class ConfirmRegisterForm(Form):
        """RegisterForm extended with UserProfile details."""

        profile = FormField(CsrfDisabledProfileForm, separator='.')

    return ConfirmRegisterForm
457892
public function execute(){
        $formOptions = $this->buildOptions();

        return $this->replaceTokens([
            ':options' => $formOptions,
            ':token_input' => true === $this->csrf ? $this->createCsrfField() : ''
        ]);
    }
266032
private function _csrf_validate()
    {

        // if CSRF protection is enabled (is not boolean FALSE)
        if ($this->form_properties['csrf_storage_method'] !== false) {

            // reference to the form submission method
            global ${'_' . $this->form_properties['method']};

            $method = & ${'_' . $this->form_properties['method']};

            // if
            if (

                // the hidden field with the CSRF token was submitted
                isset($method[$this->form_properties['csrf_token_name']]) && (

                    // CSRF token is stored in a session variable
                    ($this->form_properties['csrf_storage_method'] == 'session' &&
                    // the session variable exists
                    isset($_SESSION[$this->form_properties['csrf_cookie_name']]) &&
                    // the session variable holds an array
                    is_array($_SESSION[$this->form_properties['csrf_cookie_name']]) &&
                    // the array has 2 entries
                    count($_SESSION[$this->form_properties['csrf_cookie_name']]) == 2 &&
                    // the value of the hidden field and the value in the session match
                    $method[$this->form_properties['csrf_token_name']] == $_SESSION[$this->form_properties['csrf_cookie_name']][0] &&
                    // if CSRF token doesn't expire or it does but it didn't yet
                    ($_SESSION[$this->form_properties['csrf_cookie_name']][1] == 0 || $_SESSION[$this->form_properties['csrf_cookie_name']][1] > time()))

                    ||

                    // CSRF token is stored in a cookie
                    ($this->form_properties['csrf_storage_method'] == 'cookie' &&
                    // the cookie exists
                    isset($_COOKIE[$this->form_properties['csrf_cookie_name']]) &&
                    // the value of the hidden field and the value in the cookie match
                    $method[$this->form_properties['csrf_token_name']] == $_COOKIE[$this->form_properties['csrf_cookie_name']])

                )

            // everything seems in order, then
            ) return true;

            // if we get here something was fishy...
            return false;

        }

        // if protection against CSRF attacks is not enabled, pretend nothing happened
        return true;

    }
45828
protected function renderCsrfTokenField()
    {
        if (strtolower($this->arguments['method']) === 'get') {
            return '';
        }
        if (!$this->securityContext->isInitialized() || !$this->authenticationManager->isAuthenticated()) {
            return '';
        }
        $csrfToken = $this->securityContext->getCsrfProtectionToken();
        return '<input type="hidden" name="__csrfToken" value="' . htmlspecialchars($csrfToken) . '" />' . chr(10);
    }
920094
protected function prepareForValidation(): void
    {
        $data = $this->all();

        // Set abilities
        if (! empty($data['abilities'])) {
            if ($this->user($this->route('guard'))->can('grant', \Cortex\Auth\Models\Ability::class)) {
                $abilities = array_map('intval', $this->get('abilities', []));
                $data['abilities'] = $this->user($this->route('guard'))->isA('superadmin') ? $abilities
                    : $this->user($this->route('guard'))->getAbilities()->pluck('id')->intersect($abilities)->toArray();
            } else {
                unset($data['abilities']);
            }
        }

        $this->replace($data);
    }
875933
protected function addCsrfElement()
    {
        if ($this->has('csrf')) {
            return;
        }

        $spec = array_replace_recursive($this->csrfElementSpec, [
                'name' => $this->getCsrfElementName(),
                'options' => [
                    'csrf_options' => [
                        'timeout' => $this->getFormTimeout(),
                    ],
                ],
            ]);

        $this->add($spec, ['priority' => -980]);
    }
329200
protected function generateToken()
    {
        if ($this->token === null) {
            $secret = array(
                'install' => __DIR__,
                'name' => $this->name,
            );

            if (isset($_SESSION)) {
                $key = sha1(__DIR__ . '/' . 'formidable_secret');

                if (isset($_SESSION[$key])) {
                    $secret['csrf'] = $_SESSION[$key];
                } else {
                    $csrf = sha1(uniqid(mt_rand(), true).'|'.gettimeofday(true));
                    $_SESSION[$key] = $csrf;
                    $secret['csrf'] = $csrf;
                }
            }

            $this->token = sha1(serialize($secret));
        }
    }
667432
def csrf_protect(f):
    """"""

    @wraps(f)
    def wrapper(*args, **kwargs):
        token = session.get("csrf_token", None)
        if token is None or token != request.environ.get("HTTP_X_CSRFTOKEN"):
            logger.warning("Received invalid csrf token. Aborting")
            abort(403)
        # call original request handler
        return f(*args, **kwargs)

    return wrapper
1275221
protected function loadSessionToken()
    {
        if (null === $this->csrfTokenValue = $this->session->getData($this->csrfTokenName)) {
            $this->csrfTokenValue = $this->generateToken();
            $this->session->setData($this->csrfTokenName, $this->csrfTokenValue);
        }
    }
449788
public function methodWather()
  {
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
      if (!isset($_POST['csrf_token'])) {
        $this->errors[] = 'CSRF token not found!';
      } elseif (!hash_equals($_POST['csrf_token'], $_SESSION['csrf_token'])) {
        $this->errors[] = 'CSRF token not valid!';
      }
      if (!empty($this->errors)) {
        exit(array_shift($this->errors));
      }
    }
  }
75776
private function renderCsrfToken() {
		
		$tokenManager = new CsrfTokenManager();
		$token = $tokenManager->refreshToken('_' . $this->action . '_');

		$e = new InputElement(self::CSRF_TOKEN_NAME, $token->getValue());
		$e->setAttribute('type', 'hidden');
		
		return $e->render();
	}
105583
public function getCsrfToken() {
		if (!isset($_SESSION[$this->csrfTokenSessionKey])) {
			$this->generateCsrfToken();
		}
		return $_SESSION[$this->csrfTokenSessionKey];
	}
276957
protected function establishCSRFTokenState()
    {
        $storage = $this->getStorage();
        if ($storage->get('state') === null) {
            $storage->set('state', md5(uniqid(mt_rand(), true)));
        }
    }
1074832
public function afterHandle($event)
    {
        parent::afterHandle($event);
        
        // reset form_token
        if ($this->request->getMethod() === 'POST') {
            
            if ($this->errorInfo && !$this->errorInfo['errcode'] && $this->options['csrfTokenEnabled'] && $this->options['csrfTokenAutoReset']) {
                $this->resetCsrfToken();
            }
        }
    }