Token.php 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. <?php
  2. App::uses('ToolsAppModel', 'Tools.Model');
  3. App::uses('CommonComponent', 'Tools.Controller/Component');
  4. App::uses('Hash', 'Utility');
  5. /**
  6. * A generic model to hold tokens
  7. *
  8. * @author Mark Scherer
  9. * @cakephp 2.x
  10. * @license MIT
  11. */
  12. class Token extends ToolsAppModel {
  13. public $displayField = 'key';
  14. public $order = array('Token.created' => 'DESC');
  15. public $defaultLength = 22;
  16. public $validity = MONTH;
  17. public $validate = array(
  18. 'type' => array(
  19. 'notEmpty' => array(
  20. 'rule' => array('notEmpty'),
  21. 'message' => 'valErrMandatoryField',
  22. ),
  23. ),
  24. 'key' => array(
  25. 'notEmpty' => array(
  26. 'rule' => array('notEmpty'),
  27. 'message' => 'valErrMandatoryField',
  28. 'last' => true,
  29. ),
  30. 'isUnique' => array(
  31. 'rule' => array('isUnique'),
  32. 'message' => 'valErrTokenExists',
  33. ),
  34. ),
  35. 'content' => array(
  36. 'maxLength' => array(
  37. 'rule' => array('maxLength', 255),
  38. 'message' => array('valErrMaxCharacters %s', 255),
  39. 'allowEmpty' => true
  40. ),
  41. ),
  42. 'used' => array('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 = array(
  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 = array('conditions' => array($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 boolean Success
  134. */
  135. public function spendKey($id = null) {
  136. if (empty($id)) {
  137. return false;
  138. }
  139. //$this->id = $id;
  140. if ($this->updateAll(array($this->alias . '.used' => $this->alias . '.used + 1', $this->alias . '.modified' => '"' . date(FORMAT_DB_DATETIME) . '"'), array($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 boolean success
  150. */
  151. public function garbageCollector() {
  152. $conditions = array(
  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. public function stats() {
  161. $keys = array();
  162. $keys['unused_valid'] = $this->find('count', array('conditions' => array($this->alias . '.used' => 0, $this->alias . '.created >=' => date(FORMAT_DB_DATETIME, time() - $this->validity))));
  163. $keys['used_valid'] = $this->find('count', array('conditions' => array($this->alias . '.used' => 1, $this->alias . '.created >=' => date(FORMAT_DB_DATETIME, time() - $this->validity))));
  164. $keys['unused_invalid'] = $this->find('count', array('conditions' => array($this->alias . '.used' => 0, $this->alias . '.created <' => date(FORMAT_DB_DATETIME, time() - $this->validity))));
  165. $keys['used_invalid'] = $this->find('count', array('conditions' => array($this->alias . '.used' => 1, $this->alias . '.created <' => date(FORMAT_DB_DATETIME, time() - $this->validity))));
  166. $types = $this->find('all', array('conditions' => array(), 'fields' => array('DISTINCT type')));
  167. $keys['types'] = !empty($types) ? Hash::extract('{n}.' . $this->alias . '.type', $types) : array();
  168. return $keys;
  169. }
  170. /**
  171. * Generator
  172. *
  173. * @param length (defaults to defaultLength)
  174. * @return string Key
  175. */
  176. public function generateKey($length = null) {
  177. if (empty($length)) {
  178. $length = $this->defaultLength;
  179. }
  180. App::uses('RandomLib', 'Tools.Lib');
  181. return RandomLib::generatePassword($length);
  182. }
  183. }