TYPO3 CMS  TYPO3_7-6
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 
18 
26 abstract class AbstractFormProtection
27 {
32 
38  protected $sessionToken;
39 
43  protected function getSessionToken()
44  {
45  if ($this->sessionToken === null) {
46  $this->sessionToken = $this->retrieveSessionToken();
47  }
48  return $this->sessionToken;
49  }
50 
54  public function __destruct()
55  {
56  unset($this->sessionToken);
57  }
58 
66  public function clean()
67  {
68  unset($this->sessionToken);
69  $this->persistSessionToken();
70  }
71 
85  public function generateToken($formName, $action = '', $formInstanceName = '')
86  {
87  if ($formName == '') {
88  throw new \InvalidArgumentException('$formName must not be empty.', 1294586643);
89  }
90  $tokenId = GeneralUtility::hmac($formName . $action . $formInstanceName . $this->getSessionToken());
91  return $tokenId;
92  }
93 
104  public function validateToken($tokenId, $formName, $action = '', $formInstanceName = '')
105  {
106  $validTokenId = GeneralUtility::hmac(((string)$formName . (string)$action) . (string)$formInstanceName . $this->getSessionToken());
107  if ((string)$tokenId === $validTokenId) {
108  $isValid = true;
109  } else {
110  $isValid = false;
111  }
112  if (!$isValid) {
114  }
115  return $isValid;
116  }
117 
123  protected function generateSessionToken()
124  {
125  return bin2hex(GeneralUtility::generateRandomBytes(32));
126  }
127 
134  protected function createValidationErrorMessage()
135  {
136  if ($this->validationFailedCallback !== null) {
137  $this->validationFailedCallback->__invoke();
138  }
139  }
140 
146  abstract protected function retrieveSessionToken();
147 
155  abstract public function persistSessionToken();
156 }
generateToken($formName, $action='', $formInstanceName='')
validateToken($tokenId, $formName, $action='', $formInstanceName='')
static hmac($input, $additionalSecret='')
static generateRandomBytes($bytesToReturn)