Skip to content

Commit ef8ae0e

Browse files
committed
CsrfProtection: auto-starts session before form is rendered [Closes #239]
1 parent 519ad85 commit ef8ae0e

File tree

2 files changed

+15
-16
lines changed

2 files changed

+15
-16
lines changed

src/Forms/Controls/CsrfProtection.php

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ class CsrfProtection extends HiddenField
2020
{
2121
public const PROTECTION = 'Nette\Forms\Controls\CsrfProtection::validateCsrf';
2222

23-
/** @var Nette\Http\Session */
23+
/** @var Nette\Http\Session|null */
2424
public $session;
2525

2626

@@ -37,6 +37,14 @@ public function __construct($errorMessage)
3737
$this->monitor(Presenter::class, function (Presenter $presenter): void {
3838
if (!$this->session) {
3939
$this->session = $presenter->getSession();
40+
$this->session->start();
41+
}
42+
});
43+
44+
$this->monitor(Nette\Forms\Form::class, function (Nette\Forms\Form $form): void {
45+
if (!$this->session && !$form instanceof Nette\Application\UI\Form) {
46+
$this->session = new Nette\Http\Session($form->httpRequest, new Nette\Http\Response);
47+
$this->session->start();
4048
}
4149
});
4250
}
@@ -60,11 +68,14 @@ public function loadHttpData(): void
6068

6169
public function getToken(): string
6270
{
63-
$session = $this->getSession()->getSection(__CLASS__);
71+
if (!$this->session) {
72+
throw new Nette\InvalidStateException('Session initialization error');
73+
}
74+
$session = $this->session->getSection(__CLASS__);
6475
if (!isset($session->token)) {
6576
$session->token = Nette\Utils\Random::generate();
6677
}
67-
return $session->token ^ $this->getSession()->getId();
78+
return $session->token ^ $this->session->getId();
6879
}
6980

7081

@@ -89,16 +100,4 @@ public static function validateCsrf(self $control): bool
89100
$value = (string) $control->getValue();
90101
return $control->generateToken(substr($value, 0, 10)) === $value;
91102
}
92-
93-
94-
/********************* backend ****************d*g**/
95-
96-
97-
private function getSession(): Nette\Http\Session
98-
{
99-
if (!$this->session) {
100-
$this->session = new Nette\Http\Session($this->getForm()->httpRequest, new Nette\Http\Response);
101-
}
102-
return $this->session;
103-
}
104103
}

src/Forms/Form.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ class Form extends Container implements Nette\Utils\IHtmlString
9393
/** @var callable[]&(callable(Form): void)[]; Occurs before the form is rendered */
9494
public $onRender;
9595

96-
/** @var Nette\Http\IRequest used only by standalone form */
96+
/** @internal @var Nette\Http\IRequest used only by standalone form */
9797
public $httpRequest;
9898

9999
/** @var mixed or null meaning: not detected yet */

0 commit comments

Comments
 (0)