-
-
Notifications
You must be signed in to change notification settings - Fork 147
Expand file tree
/
Copy pathCsrfProtection.php
More file actions
115 lines (88 loc) · 2.21 KB
/
CsrfProtection.php
File metadata and controls
115 lines (88 loc) · 2.21 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\Forms\Controls;
use Nette;
/**
* CSRF protection field.
*/
class CsrfProtection extends HiddenField
{
public const PROTECTION = 'Nette\Forms\Controls\CsrfProtection::validateCsrf';
/** @var Nette\Http\Session */
public $session;
/**
* @param string|object
*/
public function __construct($errorMessage)
{
parent::__construct();
$this->setOmitted()
->setRequired()
->addRule(self::PROTECTION, $errorMessage);
$this->monitor(Nette\Application\UI\Presenter::class);
}
protected function attached(Nette\ComponentModel\IComponent $parent): void
{
parent::attached($parent);
if (!$this->session && $parent instanceof Nette\Application\UI\Presenter) {
$this->session = $parent->getSession();
}
}
/**
* @return static
* @internal
*/
public function setCurrentValue($value)
{
return $this;
}
/**
* Loads HTTP data.
*/
public function loadHttpData(): void
{
$this->value = $this->getHttpData(Nette\Forms\Form::DATA_TEXT);
}
public function getToken(): string
{
$session = $this->getSession()->getSection(__CLASS__);
if (!isset($session->token)) {
$session->token = Nette\Utils\Random::generate();
}
return $session->token ^ $this->getSession()->getId();
}
private function generateToken($random = null): string
{
if ($random === null) {
$random = Nette\Utils\Random::generate(10);
}
return $random . base64_encode(sha1($this->getToken() . $random, true));
}
/**
* Generates control's HTML element.
*/
public function getControl(): Nette\Utils\Html
{
return parent::getControl()->value($this->generateToken());
}
/**
* @internal
*/
public static function validateCsrf(self $control): bool
{
$value = (string) $control->getValue();
return $control->generateToken(substr($value, 0, 10)) === $value;
}
/********************* backend ****************d*g**/
private function getSession(): Nette\Http\Session
{
if (!$this->session) {
$this->session = new Nette\Http\Session($this->getForm()->httpRequest, new Nette\Http\Response);
}
return $this->session;
}
}