forkbb/app/Core/Csrf.php

70 lines
1.5 KiB
PHP
Raw Normal View History

2017-02-14 13:05:26 +00:00
<?php
2017-03-21 16:16:15 +00:00
namespace ForkBB\Core;
2017-02-14 13:05:26 +00:00
use ForkBB\Core\Secury;
class Csrf
{
/**
* @var Secury
*/
protected $secury;
/**
* @var string
*/
protected $key;
/**
* Конструктор
2017-11-03 13:06:22 +00:00
*
2017-02-14 13:05:26 +00:00
* @param Secury $secury
* @param string $key
2017-02-14 13:05:26 +00:00
*/
public function __construct(Secury $secury, string $key)
2017-02-14 13:05:26 +00:00
{
$this->secury = $secury;
2018-03-08 12:39:54 +00:00
$this->key = \sha1($key);
2017-02-14 13:05:26 +00:00
}
/**
* Возвращает csrf токен
2017-11-03 13:06:22 +00:00
*
2017-02-14 13:05:26 +00:00
* @param string $marker
* @param array $args
* @param string|int $time
2017-11-03 13:06:22 +00:00
*
2017-02-14 13:05:26 +00:00
* @return string
*/
public function create(string $marker, array $args = [], $time = null): string
2017-02-14 13:05:26 +00:00
{
unset($args['token'], $args['#']);
2018-03-08 12:39:54 +00:00
\ksort($args);
2017-04-09 14:32:49 +00:00
$marker .= '|';
foreach ($args as $key => $value) {
$marker .= $key . '|' . (string) $value . '|';
}
2018-03-08 12:39:54 +00:00
$time = $time ?: \time();
2017-04-09 14:32:49 +00:00
return $this->secury->hmac($marker, $time . $this->key) . 'f' . $time;
2017-02-14 13:05:26 +00:00
}
/**
* Проверка токена
2017-11-03 13:06:22 +00:00
*
2017-02-16 13:26:15 +00:00
* @param mixed $token
2017-02-14 13:05:26 +00:00
* @param string $marker
* @param array $args
2017-11-03 13:06:22 +00:00
*
2017-02-14 13:05:26 +00:00
* @return bool
*/
public function verify($token, string $marker, array $args = []): bool
2017-02-14 13:05:26 +00:00
{
2018-03-08 12:39:54 +00:00
return \is_string($token)
&& \preg_match('%f(\d+)$%D', $token, $matches)
&& $matches[1] < \time()
&& $matches[1] + 1800 > \time()
&& \hash_equals($this->create($marker, $args, $matches[1]), $token);
2017-02-14 13:05:26 +00:00
}
}