Fix csrf on hand made error

develop
sheychen 2018-06-27 19:20:18 +02:00
parent 63a448fb49
commit 58959c6d00
1 changed files with 16 additions and 10 deletions

View File

@ -17,13 +17,7 @@ class Form {
public function __construct(string $name, string $path, string $extention = null, bool $folder = true, array $sets = array()){
$this->name = $name;
if(session_status() == PHP_SESSION_NONE) session_start(); //TODO: create Krutsh\Session
if(isset($_SESSION[static::$csrfSession][$name])){
$this->csrfToken = $_SESSION[static::$csrfSession][$name];
}else{
$this->csrfToken = base64_encode(random_bytes(6));
$_SESSION[static::$csrfSession][$name] = $this->csrfToken;
}
$this->resetCsrf();
$tpl = new Html($path, $extention, $folder);
$tpl->set($name, $this)
->sets($sets)
@ -31,6 +25,16 @@ class Form {
return $this;
}
public function resetCsrf(){
if(session_status() == PHP_SESSION_NONE) session_start(); //TODO: create Krutsh\Session
if(isset($_SESSION[static::$csrfSession][$this->name])){
$this->csrfToken = $_SESSION[static::$csrfSession][$this->name];
}else{
$this->csrfToken = base64_encode(random_bytes(6));
$_SESSION[static::$csrfSession][$this->name] = $this->csrfToken;
}
}
public static function sanitize(array $data) : array{
$return = array();
foreach($data as $key => $value){
@ -52,7 +56,7 @@ class Form {
$value = isset($data[$element->name()]) ? $data[$element->name()] : null;
$return = $element->valid($value);
if($return !== true){
$this->error('Le champ '.$element->name().' est '.$return.'.');
$this->error('Le champ '.$element->name().' est '.$return.'.', false);
$valid = false;
}else{
$element->value($value);
@ -60,12 +64,14 @@ class Form {
}
if($valid)
unset($_SESSION[static::$csrfSession][$this->name]);
return $valid;
}
public function error(string $error){
public function error(string $error, bool $reset = true){
$this->errors[] = $error;
if($reset)
$this->resetCsrf();
}
public function name() : string{