Token.php 5.6 KB

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