TokensTable.php 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. <?php
  2. namespace Tools\Model\Table;
  3. use Tools\Model\Table\Table;
  4. use Tools\Utility\Random;
  5. use Cake\Utility\Hash;
  6. /**
  7. * A generic model to hold tokens
  8. *
  9. * @author Mark Scherer
  10. * @license http://opensource.org/licenses/mit-license.php MIT
  11. */
  12. class TokensTable extends Table {
  13. public $displayField = 'key';
  14. public $order = ['created' => 'DESC'];
  15. public $defaultLength = 22;
  16. public $validity = MONTH;
  17. public $validate = [
  18. 'type' => [
  19. 'notBlank' => [
  20. 'rule' => 'notBlank',
  21. 'message' => 'valErrMandatoryField',
  22. ],
  23. ],
  24. 'key' => [
  25. 'notBlank' => [
  26. 'rule' => ['notBlank'],
  27. 'message' => 'valErrMandatoryField',
  28. 'last' => true,
  29. ],
  30. 'isUnique' => [
  31. 'rule' => ['isUnique'],
  32. 'message' => 'valErrTokenExists',
  33. ],
  34. ],
  35. 'content' => [
  36. 'maxLength' => [
  37. 'rule' => ['maxLength', 255],
  38. 'message' => ['valErrMaxCharacters {0}', 255],
  39. 'allowEmpty' => true
  40. ],
  41. ],
  42. 'used' => ['numeric']
  43. ];
  44. /**
  45. * Stores new key in DB
  46. *
  47. * @param string $type: necessary
  48. * @param string|null $key: optional key, otherwise a key will be generated
  49. * @param mixed|null $uid: optional (if used, only this user can use this key)
  50. * @param string|null $content: up to 255 characters of content may be added (optional)
  51. * NOW: checks if this key is already used (should be unique in table)
  52. * @return string key on SUCCESS, boolean false otherwise
  53. */
  54. public function newKey($type, $key = null, $uid = null, $content = null) {
  55. if (empty($type)) {
  56. return false;
  57. }
  58. if (empty($key)) {
  59. $key = $this->generateKey($this->defaultLength);
  60. $keyLength = $this->defaultLength;
  61. } else {
  62. $keyLength = mb_strlen($key);
  63. }
  64. $data = [
  65. 'type' => $type,
  66. 'user_id' => (string)$uid,
  67. 'content' => (string)$content,
  68. 'key' => $key,
  69. ];
  70. $entity = $this->newEntity($data);
  71. $max = 99;
  72. while (!$this->save($entity)) {
  73. $entity['key'] = $this->generateKey($keyLength);
  74. $max--;
  75. if ($max === 0) {
  76. return false;
  77. }
  78. }
  79. return $entity['key'];
  80. }
  81. /**
  82. * UsesKey (only once!) - by KEY
  83. *
  84. * @param string $type : necessary
  85. * @param string $key : necessary
  86. * @param mixed|null $uid : needs to be provided if this key has a user_id stored
  87. * @param bool $treatUsedAsInvalid
  88. * @return array Content - if successfully used or if already used (used=1), FALSE else
  89. */
  90. public function useKey($type, $key, $uid = null, $treatUsedAsInvalid = false) {
  91. if (empty($type) || empty($key)) {
  92. return false;
  93. }
  94. $options = ['conditions' => [$this->alias() . '.key' => $key, $this->alias() . '.type' => $type]];
  95. if (!empty($uid)) {
  96. $options['conditions'][$this->alias() . '.user_id'] = $uid;
  97. }
  98. $res = $this->find('first', $options);
  99. if (empty($res)) {
  100. return false;
  101. }
  102. if (!empty($uid) && !empty($res['user_id']) && $res['user_id'] != $uid) {
  103. // return $res; # more secure to fail here if user_id is not provided, but was submitted prev.
  104. return false;
  105. }
  106. // already used?
  107. if (!empty($res['used'])) {
  108. if ($treatUsedAsInvalid) {
  109. return false;
  110. }
  111. // return true and let the application check what to do then
  112. return $res;
  113. }
  114. // actually spend key (set to used)
  115. if ($this->spendKey($res['id'])) {
  116. return $res;
  117. }
  118. // no limit? we dont spend key then
  119. if (!empty($res['unlimited'])) {
  120. return $res;
  121. }
  122. //$this->log('VIOLATION in ' . $this->alias() . ' Model (method useKey)');
  123. return false;
  124. }
  125. /**
  126. * Sets Key to "used" (only once!) - directly by ID
  127. *
  128. * @param int $id Id of key to spend: necessary
  129. * @return bool Success
  130. */
  131. public function spendKey($id) {
  132. if (empty($id)) {
  133. return false;
  134. }
  135. //$expression = new \Cake\Database\Expression\QueryExpression(['used = used + 1', 'modified' => date(FORMAT_DB_DATETIME)]);
  136. $result = $this->updateAll(
  137. ['used = used + 1', 'modified' => date(FORMAT_DB_DATETIME)],
  138. ['id' => $id]
  139. );
  140. if ($result) {
  141. return true;
  142. }
  143. return false;
  144. }
  145. /**
  146. * Remove old/invalid keys
  147. * does not remove recently used ones (for proper feedback)!
  148. *
  149. * @return bool success
  150. */
  151. public function garbageCollector() {
  152. $conditions = [
  153. $this->alias() . '.created <' => date(FORMAT_DB_DATETIME, time() - $this->validity),
  154. ];
  155. return $this->deleteAll($conditions);
  156. }
  157. /**
  158. * Get admin stats
  159. *
  160. * @return array
  161. */
  162. public function stats() {
  163. $keys = [];
  164. $keys['unused_valid'] = $this->find('count', ['conditions' => [$this->alias() . '.used' => 0, $this->alias() . '.created >=' => date(FORMAT_DB_DATETIME, time() - $this->validity)]]);
  165. $keys['used_valid'] = $this->find('count', ['conditions' => [$this->alias() . '.used' => 1, $this->alias() . '.created >=' => date(FORMAT_DB_DATETIME, time() - $this->validity)]]);
  166. $keys['unused_invalid'] = $this->find('count', ['conditions' => [$this->alias() . '.used' => 0, $this->alias() . '.created <' => date(FORMAT_DB_DATETIME, time() - $this->validity)]]);
  167. $keys['used_invalid'] = $this->find('count', ['conditions' => [$this->alias() . '.used' => 1, $this->alias() . '.created <' => date(FORMAT_DB_DATETIME, time() - $this->validity)]]);
  168. $types = $this->find('all', ['conditions' => [], 'fields' => ['DISTINCT type']]);
  169. $keys['types'] = !empty($types) ? Hash::extract('{n}.type', $types) : [];
  170. return $keys;
  171. }
  172. /**
  173. * Generator of secure random tokens.
  174. *
  175. * Note that it is best to use an even number for the length.
  176. *
  177. * @param int|null $length (defaults to defaultLength)
  178. * @return string Key
  179. */
  180. public function generateKey($length = null) {
  181. if (empty($length)) {
  182. $length = $this->defaultLength;
  183. }
  184. $function = 'Random::pwd';
  185. if (version_compare(PHP_VERSION, '7.0.0') >= 0) {
  186. $function = 'random_bytes';
  187. } elseif (extension_loaded('openssl')) {
  188. $function = 'openssl_random_pseudo_bytes';
  189. } else {
  190. trigger_error('Not secure', E_USER_DEPRECATED);
  191. return Random::pwd($length);
  192. }
  193. $value = bin2hex($function($length / 2));
  194. if (strlen($value) !== $length) {
  195. $value = str_pad($value, $length, '0');
  196. }
  197. return $value;
  198. }
  199. }