TYPO3 CMS  TYPO3_8-7
AbstractFormProtection.php
Go to the documentation of this file.
1 <?php
3 
4 /*
5  * This file is part of the TYPO3 CMS project.
6  *
7  * It is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU General Public License, either version 2
9  * of the License, or any later version.
10  *
11  * For the full copyright and license information, please read the
12  * LICENSE.txt file that was distributed with this source code.
13  *
14  * The TYPO3 project - inspiring people to share!
15  */
16 
19 
27 abstract class AbstractFormProtection
28 {
33 
39  protected $sessionToken;
40 
44  protected function getSessionToken()
45  {
46  if ($this->sessionToken === null) {
47  $this->sessionToken = $this->retrieveSessionToken();
48  }
49  return $this->sessionToken;
50  }
51 
55  public function __destruct()
56  {
57  unset($this->sessionToken);
58  }
59 
65  public function clean()
66  {
67  unset($this->sessionToken);
68  $this->persistSessionToken();
69  }
70 
84  public function generateToken($formName, $action = '', $formInstanceName = '')
85  {
86  if ($formName == '') {
87  throw new \InvalidArgumentException('$formName must not be empty.', 1294586643);
88  }
89  $tokenId = GeneralUtility::hmac($formName . $action . $formInstanceName . $this->getSessionToken());
90  return $tokenId;
91  }
92 
103  public function validateToken($tokenId, $formName, $action = '', $formInstanceName = '')
104  {
105  $validTokenId = GeneralUtility::hmac(((string)$formName . (string)$action) . (string)$formInstanceName . $this->getSessionToken());
106  if (hash_equals($validTokenId, (string)$tokenId)) {
107  $isValid = true;
108  } else {
109  $isValid = false;
110  }
111  if (!$isValid) {
113  }
114  return $isValid;
115  }
116 
122  protected function generateSessionToken()
123  {
124  return GeneralUtility::makeInstance(Random::class)->generateRandomHexString(64);
125  }
126 
131  protected function createValidationErrorMessage()
132  {
133  if ($this->validationFailedCallback !== null) {
134  $this->validationFailedCallback->__invoke();
135  }
136  }
137 
143  abstract protected function retrieveSessionToken();
144 
151  abstract public function persistSessionToken();
152 }
generateToken($formName, $action='', $formInstanceName='')
validateToken($tokenId, $formName, $action='', $formInstanceName='')
static hmac($input, $additionalSecret='')
static makeInstance($className,... $constructorArguments)