Token.php 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. <?php
  2. App::uses('ToolsAppModel', 'Tools.Model');
  3. App::uses('CommonComponent', 'Tools.Controller/Component');
  4. App::uses('Hash', 'Utility');
  5. App::uses('RandomLib', 'Tools.Lib');
  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 Token extends ToolsAppModel {
  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. $this->set($data);
  71. $max = 99;
  72. while (!$this->validates()) {
  73. $data['key'] = $this->generateKey($keyLength);
  74. $this->set($data);
  75. $max--;
  76. if ($max === 0) {
  77. return false;
  78. }
  79. }
  80. $this->create();
  81. if ($this->save($data)) {
  82. return $key;
  83. }
  84. return false;
  85. }
  86. /**
  87. * UsesKey (only once!) - by KEY
  88. *
  89. * @param string type: necessary
  90. * @param string key: necessary
  91. * @param mixed user_id: needs to be provided if this key has a user_id stored
  92. * @return array Content - if successfully used or if already used (used=1), FALSE else
  93. */
  94. public function useKey($type, $key, $uid = null, $treatUsedAsInvalid = false) {
  95. if (empty($type) || empty($key)) {
  96. return false;
  97. }
  98. $options = ['conditions' => [$this->alias . '.key' => $key, $this->alias . '.type' => $type]];
  99. if (!empty($uid)) {
  100. $options['conditions'][$this->alias . '.user_id'] = $uid;
  101. }
  102. $res = $this->find('first', $options);
  103. if (empty($res)) {
  104. return false;
  105. }
  106. if (!empty($uid) && !empty($res[$this->alias]['user_id']) && $res[$this->alias]['user_id'] != $uid) {
  107. // return $res; # more secure to fail here if user_id is not provided, but was submitted prev.
  108. return false;
  109. }
  110. // already used?
  111. if (!empty($res[$this->alias]['used'])) {
  112. if ($treatUsedAsInvalid) {
  113. return false;
  114. }
  115. // return true and let the application check what to do then
  116. return $res;
  117. }
  118. // actually spend key (set to used)
  119. if ($this->spendKey($res[$this->alias]['id'])) {
  120. return $res;
  121. }
  122. // no limit? we dont spend key then
  123. if (!empty($res[$this->alias]['unlimited'])) {
  124. return $res;
  125. }
  126. $this->log('VIOLATION in ' . $this->alias . ' Model (method useKey)');
  127. return false;
  128. }
  129. /**
  130. * Sets Key to "used" (only once!) - directly by ID
  131. *
  132. * @param id of key to spend: necessary
  133. * @return bool Success
  134. */
  135. public function spendKey($id = null) {
  136. if (empty($id)) {
  137. return false;
  138. }
  139. //$this->id = $id;
  140. if ($this->updateAll([$this->alias . '.used' => $this->alias . '.used + 1', $this->alias . '.modified' => '"' . date(FORMAT_DB_DATETIME) . '"'], [$this->alias . '.id' => $id])) {
  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, false);
  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}.' . $this->alias . '.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. if (version_compare(PHP_VERSION, '7.0.0') >= 0) {
  185. $function = 'random_bytes';
  186. } elseif (extension_loaded('openssl')) {
  187. $function = 'openssl_random_pseudo_bytes';
  188. } else {
  189. trigger_error('Not secure', E_USER_DEPRECATED);
  190. return RandomLib::generatePassword($length);
  191. }
  192. $value = bin2hex($function($length / 2));
  193. if (strlen($value) !== $length) {
  194. $value = str_pad($value, $length, '0');
  195. }
  196. return $value;
  197. }
  198. }