TokensTable.php 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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 %s', 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 key: optional key, otherwise a key will be generated
  49. * @param mixed user_id: optional (if used, only this user can use this key)
  50. * @param string 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 user_id: needs to be provided if this key has a user_id stored
  87. * @return array Content - if successfully used or if already used (used=1), FALSE else
  88. */
  89. public function useKey($type, $key, $uid = null, $treatUsedAsInvalid = false) {
  90. if (empty($type) || empty($key)) {
  91. return false;
  92. }
  93. $options = ['conditions' => [$this->alias() . '.key' => $key, $this->alias() . '.type' => $type]];
  94. if (!empty($uid)) {
  95. $options['conditions'][$this->alias() . '.user_id'] = $uid;
  96. }
  97. $res = $this->find('first', $options);
  98. if (empty($res)) {
  99. return false;
  100. }
  101. if (!empty($uid) && !empty($res['user_id']) && $res['user_id'] != $uid) {
  102. // return $res; # more secure to fail here if user_id is not provided, but was submitted prev.
  103. return false;
  104. }
  105. // already used?
  106. if (!empty($res['used'])) {
  107. if ($treatUsedAsInvalid) {
  108. return false;
  109. }
  110. // return true and let the application check what to do then
  111. return $res;
  112. }
  113. // actually spend key (set to used)
  114. if ($this->spendKey($res['id'])) {
  115. return $res;
  116. }
  117. // no limit? we dont spend key then
  118. if (!empty($res['unlimited'])) {
  119. return $res;
  120. }
  121. $this->log('VIOLATION in ' . $this->alias() . ' Model (method useKey)');
  122. return false;
  123. }
  124. /**
  125. * Sets Key to "used" (only once!) - directly by ID
  126. *
  127. * @param id of key to spend: necessary
  128. * @return bool Success
  129. */
  130. public function spendKey($id) {
  131. if (empty($id)) {
  132. return false;
  133. }
  134. //$expression = new \Cake\Database\Expression\QueryExpression(['used = used + 1', 'modified' => date(FORMAT_DB_DATETIME)]);
  135. if ($x = $this->updateAll(
  136. ['used = used + 1', 'modified' => date(FORMAT_DB_DATETIME)],
  137. [$this->alias() . '.id' => $id])
  138. ) {
  139. return true;
  140. }
  141. return false;
  142. }
  143. /**
  144. * Remove old/invalid keys
  145. * does not remove recently used ones (for proper feedback)!
  146. *
  147. * @return bool success
  148. */
  149. public function garbageCollector() {
  150. $conditions = [
  151. $this->alias() . '.created <' => date(FORMAT_DB_DATETIME, time() - $this->validity),
  152. ];
  153. return $this->deleteAll($conditions, false);
  154. }
  155. /**
  156. * Get admin stats
  157. */
  158. public function stats() {
  159. $keys = [];
  160. $keys['unused_valid'] = $this->find('count', ['conditions' => [$this->alias() . '.used' => 0, $this->alias() . '.created >=' => date(FORMAT_DB_DATETIME, time() - $this->validity)]]);
  161. $keys['used_valid'] = $this->find('count', ['conditions' => [$this->alias() . '.used' => 1, $this->alias() . '.created >=' => date(FORMAT_DB_DATETIME, time() - $this->validity)]]);
  162. $keys['unused_invalid'] = $this->find('count', ['conditions' => [$this->alias() . '.used' => 0, $this->alias() . '.created <' => date(FORMAT_DB_DATETIME, time() - $this->validity)]]);
  163. $keys['used_invalid'] = $this->find('count', ['conditions' => [$this->alias() . '.used' => 1, $this->alias() . '.created <' => date(FORMAT_DB_DATETIME, time() - $this->validity)]]);
  164. $types = $this->find('all', ['conditions' => [], 'fields' => ['DISTINCT type']]);
  165. $keys['types'] = !empty($types) ? Hash::extract('{n}.type', $types) : [];
  166. return $keys;
  167. }
  168. /**
  169. * Generator
  170. *
  171. * @param length (defaults to defaultLength)
  172. * @return string Key
  173. */
  174. public function generateKey($length = null) {
  175. if (empty($length)) {
  176. $length = $this->defaultLength;
  177. }
  178. return Random::pwd($length);
  179. }
  180. }