PluginProbe
Packeta / 2.0.9
Packeta v2.0.9
2.3.2 2.3.1 trunk 1.2.2 1.2.3 1.2.4 1.2.5 1.2.6 1.3.0 1.3.1 1.3.2 1.4 1.4.1 1.4.2 1.4.3 1.5.0 1.5.1 1.5.2 1.5.3 1.5.4 1.6.0 1.6.1 1.6.2 1.6.3 1.6.4 All 56 releases
packeta / deps / nette / forms / src / Forms / Controls / CsrfProtection.php

CsrfProtection.php in Packeta 2.0.9, at deps/nette/forms/src/Forms/Controls/CsrfProtection.php

81 lines 2.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 /**
4 * This file is part of the Nette Framework (https://nette.org)
5 * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6 */
7 declare (strict_types=1);
8 namespace Packetery\Nette\Forms\Controls;
9
10 use Packetery\Nette;
11 use Packetery\Nette\Application\UI\Presenter;
12 /**
13 * CSRF protection field.
14 */
15 class CsrfProtection extends HiddenField
16 {
17 public const PROTECTION = 'Packetery\\Nette\\Forms\\Controls\\CsrfProtection::validateCsrf';
18 /** @var \Packetery\Nette\Http\Session|null */
19 public $session;
20 /**
21 * @param string|object $errorMessage
22 */
23 public function __construct($errorMessage)
24 {
25 parent::__construct();
26 $this->setOmitted()->setRequired()->addRule(self::PROTECTION, $errorMessage);
27 $this->monitor(Presenter::class, function (Presenter $presenter) : void {
28 if (!$this->session) {
29 $this->session = $presenter->getSession();
30 $this->session->start();
31 }
32 });
33 $this->monitor(\Packetery\Nette\Forms\Form::class, function (\Packetery\Nette\Forms\Form $form) : void {
34 if (!$this->session && !$form instanceof \Packetery\Nette\Application\UI\Form) {
35 $this->session = new \Packetery\Nette\Http\Session($form->httpRequest, new \Packetery\Nette\Http\Response());
36 $this->session->start();
37 }
38 });
39 }
40 /**
41 * @return static
42 * @internal
43 */
44 public function setValue($value)
45 {
46 return $this;
47 }
48 public function loadHttpData() : void
49 {
50 $this->value = $this->getHttpData(\Packetery\Nette\Forms\Form::DATA_TEXT);
51 }
52 public function getToken() : string
53 {
54 if (!$this->session) {
55 throw new \Packetery\Nette\InvalidStateException('Session initialization error');
56 }
57 $session = $this->session->getSection(self::class);
58 if (!isset($session->token)) {
59 $session->token = \Packetery\Nette\Utils\Random::generate();
60 }
61 return $session->token ^ $this->session->getId();
62 }
63 private function generateToken(string $random = null) : string
64 {
65 if ($random === null) {
66 $random = \Packetery\Nette\Utils\Random::generate(10);
67 }
68 return $random . \base64_encode(\sha1($this->getToken() . $random, \true));
69 }
70 public function getControl() : \Packetery\Nette\Utils\Html
71 {
72 return parent::getControl()->value($this->generateToken());
73 }
74 /** @internal */
75 public static function validateCsrf(self $control) : bool
76 {
77 $value = (string) $control->getValue();
78 return $control->generateToken(\substr($value, 0, 10)) === $value;
79 }
80 }
81