@@ -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}
0 commit comments