php-censor/src/Form/Element/Csrf.php

41 lines
797 B
PHP
Raw Normal View History

2016-04-12 19:31:39 +02:00
<?php
2018-03-04 11:50:08 +01:00
namespace PHPCensor\Form\Element;
2016-04-21 19:05:32 +02:00
2018-02-16 14:18:04 +01:00
use PHPCensor\View;
2016-04-12 19:31:39 +02:00
class Csrf extends Hidden
{
2017-11-05 15:48:36 +01:00
/**
* @return boolean
*/
2016-04-21 19:05:32 +02:00
public function validate()
{
$sessionToken = isset($_SESSION['csrf_tokens'][$this->getName()])
? $_SESSION['csrf_tokens'][$this->getName()]
: null;
if ($this->value !== $sessionToken) {
2016-04-21 19:05:32 +02:00
return false;
}
2016-04-12 19:31:39 +02:00
2016-04-21 19:05:32 +02:00
return true;
}
2016-04-12 19:31:39 +02:00
2017-11-05 15:48:36 +01:00
/**
* @param View $view
*/
2017-01-13 16:35:41 +01:00
protected function onPreRender(View &$view)
2016-04-21 19:05:32 +02:00
{
2017-01-13 16:35:41 +01:00
parent::onPreRender($view);
2017-11-05 15:48:36 +01:00
$this->setValue(
rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=')
);
$view->value = $this->getValue();
2017-11-05 15:48:36 +01:00
$_SESSION['csrf_tokens'][$this->getName()] = $this->getValue();
2016-04-21 19:05:32 +02:00
}
}