forked from nextras/secured-links
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Helpers.php
38 lines (30 loc) · 1.06 KB
/
Helpers.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php declare(strict_types=1);
/**
* This file is part of the Nextras Secured Links library.
* @license MIT
* @link https://github.com/nextras/secured-links
*/
namespace Nextras\Application\UI;
use Nette;
use Nette\Http\Session;
class Helpers
{
/**
* Returns unique token for method and params
*/
public static function getCsrfToken(Session $session, string $controlClassName, string $method, array $params): string
{
$sessionSection = $session->getSection('Nextras.Application.UI.SecuredLinksPresenterTrait');
if (!isset($sessionSection->token)) {
$sessionSection->token = function_exists('random_bytes')
? random_bytes(16)
: Nette\Utils\Random::generate(16, "\x00-\xFF");
}
$params = Nette\Utils\Arrays::flatten($params);
$params = implode('|', array_keys($params)) . '|' . implode('|', array_values($params));
$data = $controlClassName . $method . $params . $session->getId();
$hash = hash_hmac('sha1', $data, $sessionSection->token, TRUE);
$token = strtr(substr(base64_encode($hash), 0, 8), '+/', '-_');
return $token;
}
}