Browse Source

rename CodeKey to Token

euromark 13 years ago
parent
commit
ca9ae68b5a
4 changed files with 430 additions and 210 deletions
  1. 3 210
      Model/CodeKey.php
  2. 229 0
      Model/Token.php
  3. 63 0
      Test/Case/Model/TokenTest.php
  4. 135 0
      Test/Fixture/TokenFixture.php

+ 3 - 210
Model/CodeKey.php

@@ -1,225 +1,18 @@
 <?php
-App::uses('ToolsAppModel', 'Tools.Model');
+App::uses('Token', 'Tools.Model');
 App::uses('CommonComponent', 'Tools.Controller/Component');
 
 /**
- * TODO: rename to "Token" with display field "token"
+ * @deprecated - use "Token" class
  *
  * @author Mark Scherer
  * @cakephp 2.0
  * @license MIT
  * 2011-11-17 ms
  */
-class CodeKey extends ToolsAppModel {
+class CodeKey extends Token {
 
-	public $displayField = 'key';
 	public $order = array('CodeKey.created' => 'DESC');
 
-	protected $defaultLength = 22;
-	protected $validity = MONTH;
-
-	public $validate = array(
-		'type' => array(
-			'notEmpty' => array(
-				'rule' => array('notEmpty'),
-				'message' => 'valErrMandatoryField',
-			),
-		),
-		'key' => array(
-			'notEmpty' => array(
-				'rule' => array('notEmpty'),
-				'message' => 'valErrMandatoryField',
-				'last' => true,
-			),
-			'isUnique' => array(
-				'rule' => array('isUnique'),
-				'message' => 'valErrCodeKeyExists',
-			),
-		),
-		'content' => array(
-			'maxLength' => array(
-				'rule' => array('maxLength', 255),
-				'message' => array('valErrMaxCharacters %s', 255),
-				'allowEmpty' => true
-			),
-		),
-		'used' => array('numeric')
-	);
-
-	//public $types = array('activate');
-
-	/**
-	 * stores new key in DB
-	 * @param string type: necessary
-	 * @param string key: optional key, otherwise a key will be generated
-	 * @param mixed user_id: optional (if used, only this user can use this key)
-	 * @param string content: up to 255 characters of content may be added (optional)
-	 * NOW: checks if this key is already used (should be unique in table)
-	 * @return string key on SUCCESS, boolean false otherwise
-	 * 2009-05-13 ms
-	 */
-	public function newKey($type, $key = null, $uid = null, $content = null) {
-		if (empty($type)) {		//  || !in_array($type,$this->types)
-			return false;
-		}
-
-		if (empty($key)) {
-			$key = $this->generateKey($this->defaultLength);
-			$keyLength = $this->defaultLength;
-		} else {
-			$keyLength = mb_strlen($key);
-		}
-
-		$data = array(
-			'type' => $type,
-			'user_id' => (string)$uid,
-			'content' => (string)$content,
-			'key' => $key,
-		);
-
-		$this->set($data);
-		$max = 99;
-		while (!$this->validates()) {
-			$data['key'] = $this->generateKey($keyLength);
-			$this->set($data);
-			$max--;
-			if ($max == 0) { //die('Exeption in CodeKey');
-			 	return false;
-			}
-		}
-
-		$this->create();
-		if ($this->save($data)) {
-			return $key;
-		}
-		return false;
-	}
-
-	/**
-	 * usesKey (only once!) - by KEY
-	 * @param string type: necessary
-	 * @param string key: necessary
-	 * @param mixed user_id: needs to be provided if this key has a user_id stored
-	 * @return ARRAY(content) if successfully used or if already used (used=1), FALSE else
-	 * 2009-05-13 ms
-	 */
-	public function useKey($type, $key, $uid = null, $treatUsedAsInvalid = false) {
-		if (empty($type) || empty($key)) {
-			return false;
-		}
-		$conditions = array('conditions'=>array($this->alias.'.key'=>$key,$this->alias.'.type'=>$type));
-		if (!empty($uid)) {
-			$conditions['conditions'][$this->alias.'.user_id'] = $uid;
-		}
-		$res = $this->find('first', $conditions);
-		if (empty($res)) {
-			return false;
-		}
-		if (!empty($uid) && !empty($res[$this->alias]['user_id']) && $res[$this->alias]['user_id'] != $uid) {
-			// return $res; # more secure to fail here if user_id is not provided, but was submitted prev.
-			return false;
-		}
-		# already used?
-		if (!empty($res[$this->alias]['used'])) {
-			if ($treatUsedAsInvalid) {
-				return false;
-			}
-			# return true and let the application check what to do then
-			return $res;
-		}
-		# actually spend key (set to used)
-		if ($this->spendKey($res[$this->alias]['id'])) {
-			return $res;
-		}
-		# no limit? we dont spend key then
-		if (!empty($res[$this->alias]['unlimited'])) {
-			return $res;
-		}
-		$this->log('VIOLATION in CodeKey Model (method useKey)');
-		return false;
-	}
-
-	/**
-	 * sets Key to "used" (only once!) - directly by ID
-	 * @param id of key to spend: necessary
-	 * @return boolean true on success, false otherwise
-	 * 2009-05-13 ms
-	 */
-	public function spendKey($id = null) {
-		if (empty($id)) {
-			return false;
-		}
-		//$this->id = $id;
-		if ($this->updateAll(array($this->alias.'.used' => $this->alias.'.used + 1', $this->alias.'.modified'=>'"'.date(FORMAT_DB_DATETIME).'"'), array($this->alias.'.id'=>$id))) {
-			return true;
-		}
-		return false;
-	}
-
-	/**
-	 * remove old/invalid keys
-	 * does not remove recently used ones (for proper feedback)!
-	 * @return boolean success
-	 * 2010-06-17 ms
-	 */
-	public function garbigeCollector() {
-		$conditions = array(
-			$this->alias.'.created <'=>date(FORMAT_DB_DATETIME, time()-$this->validity),
-		);
-		return $this->deleteAll($conditions, false);
-	}
-
-
-	/**
-	 * get admin stats
-	 * 2010-10-22 ms
-	 */
-	public function stats() {
-		$keys = array();
-		$keys['unused_valid'] = $this->find('count', array('conditions'=>array($this->alias.'.used'=>0, $this->alias.'.created >='=>date(FORMAT_DB_DATETIME, time()-$this->validity))));
-		$keys['used_valid'] = $this->find('count', array('conditions'=>array($this->alias.'.used'=>1, $this->alias.'.created >='=>date(FORMAT_DB_DATETIME, time()-$this->validity))));
-
-		$keys['unused_invalid'] = $this->find('count', array('conditions'=>array($this->alias.'.used'=>0, $this->alias.'.created <'=>date(FORMAT_DB_DATETIME, time()-$this->validity))));
-		$keys['used_invalid'] = $this->find('count', array('conditions'=>array($this->alias.'.used'=>1, $this->alias.'.created <'=>date(FORMAT_DB_DATETIME, time()-$this->validity))));
-
-		$types = $this->find('all', array('conditions'=>array(), 'fields'=>array('DISTINCT type')));
-		$keys['types'] = !empty($types) ? Set::extract('/'.$this->alias.'/type', $types) : array();
-		return $keys;
-	}
-
-
-	/**
-	 * @param length (defaults to defaultLength)
-	 * @return string codekey
-	 * 2009-05-13 ms
-	 */
-	public function generateKey($length = null) {
-		if (empty($length)) {
-			$length = $this->defaultLength;
-		}
-		if ((class_exists('CommonComponent') || App::import('Component', 'Common')) && method_exists('CommonComponent', 'generatePassword')) {
-			return CommonComponent::generatePassword($length);
-		} else {
-			return $this->_generateKey($length);
-		}
-	}
-
-	/**
-	 * backup method - only used if no custom function exists
-	 * 2010-06-17 ms
-	 */
-	protected function _generateKey($length = null) {
-		$chars = "234567890abcdefghijkmnopqrstuvwxyz"; // ABCDEFGHIJKLMNOPQRSTUVWXYZ
-		$i = 0;
-		$password = "";
-		$max = strlen($chars) - 1;
-
-		while ($i < $length) {
-			$password .= $chars[mt_rand(0, $max)];
-			$i++;
-		}
-		return $password;
-	}
-
 }
 

+ 229 - 0
Model/Token.php

@@ -0,0 +1,229 @@
+<?php
+App::uses('ToolsAppModel', 'Tools.Model');
+App::uses('CommonComponent', 'Tools.Controller/Component');
+
+/**
+ * A generic model to hold tokens
+ *
+ * @author Mark Scherer
+ * @cakephp 2.x
+ * @license MIT
+ * 2011-11-17 ms
+ */
+class Token extends ToolsAppModel {
+
+	public $displayField = 'key';
+	public $order = array('Token.created' => 'DESC');
+
+	protected $defaultLength = 22;
+	protected $validity = MONTH;
+
+	public $validate = array(
+		'type' => array(
+			'notEmpty' => array(
+				'rule' => array('notEmpty'),
+				'message' => 'valErrMandatoryField',
+			),
+		),
+		'key' => array(
+			'notEmpty' => array(
+				'rule' => array('notEmpty'),
+				'message' => 'valErrMandatoryField',
+				'last' => true,
+			),
+			'isUnique' => array(
+				'rule' => array('isUnique'),
+				'message' => 'valErrTokenExists',
+			),
+		),
+		'content' => array(
+			'maxLength' => array(
+				'rule' => array('maxLength', 255),
+				'message' => array('valErrMaxCharacters %s', 255),
+				'allowEmpty' => true
+			),
+		),
+		'used' => array('numeric')
+	);
+
+	//public $types = array('activate');
+
+	/**
+	 * stores new key in DB
+	 * @param string type: necessary
+	 * @param string key: optional key, otherwise a key will be generated
+	 * @param mixed user_id: optional (if used, only this user can use this key)
+	 * @param string content: up to 255 characters of content may be added (optional)
+	 * NOW: checks if this key is already used (should be unique in table)
+	 * @return string key on SUCCESS, boolean false otherwise
+	 * 2009-05-13 ms
+	 */
+	public function newKey($type, $key = null, $uid = null, $content = null) {
+		if (empty($type)) {		//  || !in_array($type,$this->types)
+			return false;
+		}
+
+		if (empty($key)) {
+			$key = $this->generateKey($this->defaultLength);
+			$keyLength = $this->defaultLength;
+		} else {
+			$keyLength = mb_strlen($key);
+		}
+
+		$data = array(
+			'type' => $type,
+			'user_id' => (string)$uid,
+			'content' => (string)$content,
+			'key' => $key,
+		);
+
+		$this->set($data);
+		$max = 99;
+		while (!$this->validates()) {
+			$data['key'] = $this->generateKey($keyLength);
+			$this->set($data);
+			$max--;
+			if ($max == 0) { //die('Exeption in Token');
+			 	return false;
+			}
+		}
+
+		$this->create();
+		if ($this->save($data)) {
+			return $key;
+		}
+		return false;
+	}
+
+	/**
+	 * usesKey (only once!) - by KEY
+	 * @param string type: necessary
+	 * @param string key: necessary
+	 * @param mixed user_id: needs to be provided if this key has a user_id stored
+	 * @return ARRAY(content) if successfully used or if already used (used=1), FALSE else
+	 * 2009-05-13 ms
+	 */
+	public function useKey($type, $key, $uid = null, $treatUsedAsInvalid = false) {
+		if (empty($type) || empty($key)) {
+			return false;
+		}
+		$conditions = array('conditions'=>array($this->alias.'.key'=>$key,$this->alias.'.type'=>$type));
+		if (!empty($uid)) {
+			$conditions['conditions'][$this->alias.'.user_id'] = $uid;
+		}
+		$res = $this->find('first', $conditions);
+		if (empty($res)) {
+			return false;
+		}
+		if (!empty($uid) && !empty($res[$this->alias]['user_id']) && $res[$this->alias]['user_id'] != $uid) {
+			// return $res; # more secure to fail here if user_id is not provided, but was submitted prev.
+			return false;
+		}
+		# already used?
+		if (!empty($res[$this->alias]['used'])) {
+			if ($treatUsedAsInvalid) {
+				return false;
+			}
+			# return true and let the application check what to do then
+			return $res;
+		}
+		# actually spend key (set to used)
+		if ($this->spendKey($res[$this->alias]['id'])) {
+			return $res;
+		}
+		# no limit? we dont spend key then
+		if (!empty($res[$this->alias]['unlimited'])) {
+			return $res;
+		}
+		$this->log('VIOLATION in '.$this->alias.' Model (method useKey)');
+		return false;
+	}
+
+	/**
+	 * sets Key to "used" (only once!) - directly by ID
+	 * @param id of key to spend: necessary
+	 * @return boolean true on success, false otherwise
+	 * 2009-05-13 ms
+	 */
+	public function spendKey($id = null) {
+		if (empty($id)) {
+			return false;
+		}
+		//$this->id = $id;
+		if ($this->updateAll(array($this->alias.'.used' => $this->alias.'.used + 1', $this->alias.'.modified'=>'"'.date(FORMAT_DB_DATETIME).'"'), array($this->alias.'.id'=>$id))) {
+			return true;
+		}
+		return false;
+	}
+
+	/**
+	 * remove old/invalid keys
+	 * does not remove recently used ones (for proper feedback)!
+	 * @return boolean success
+	 * 2010-06-17 ms
+	 */
+	public function garbigeCollector() {
+		$conditions = array(
+			$this->alias.'.created <'=>date(FORMAT_DB_DATETIME, time()-$this->validity),
+		);
+		return $this->deleteAll($conditions, false);
+	}
+
+
+	/**
+	 * get admin stats
+	 * 2010-10-22 ms
+	 */
+	public function stats() {
+		$keys = array();
+		$keys['unused_valid'] = $this->find('count', array('conditions'=>array($this->alias.'.used'=>0, $this->alias.'.created >='=>date(FORMAT_DB_DATETIME, time()-$this->validity))));
+		$keys['used_valid'] = $this->find('count', array('conditions'=>array($this->alias.'.used'=>1, $this->alias.'.created >='=>date(FORMAT_DB_DATETIME, time()-$this->validity))));
+
+		$keys['unused_invalid'] = $this->find('count', array('conditions'=>array($this->alias.'.used'=>0, $this->alias.'.created <'=>date(FORMAT_DB_DATETIME, time()-$this->validity))));
+		$keys['used_invalid'] = $this->find('count', array('conditions'=>array($this->alias.'.used'=>1, $this->alias.'.created <'=>date(FORMAT_DB_DATETIME, time()-$this->validity))));
+
+		$types = $this->find('all', array('conditions'=>array(), 'fields'=>array('DISTINCT type')));
+		$keys['types'] = !empty($types) ? Set::extract('/'.$this->alias.'/type', $types) : array();
+		return $keys;
+	}
+
+
+	/**
+	 * Generator
+	 *
+	 * TODO: move functionality into Lib class
+	 *
+	 * @param length (defaults to defaultLength)
+	 * @return string key
+	 * 2009-05-13 ms
+	 */
+	public function generateKey($length = null) {
+		if (empty($length)) {
+			$length = $this->defaultLength;
+		}
+		if ((class_exists('CommonComponent') || App::import('Component', 'Common')) && method_exists('CommonComponent', 'generatePassword')) {
+			return CommonComponent::generatePassword($length);
+		} else {
+			return $this->_generateKey($length);
+		}
+	}
+
+	/**
+	 * backup method - only used if no custom function exists
+	 * 2010-06-17 ms
+	 */
+	protected function _generateKey($length = null) {
+		$chars = "234567890abcdefghijkmnopqrstuvwxyz"; // ABCDEFGHIJKLMNOPQRSTUVWXYZ
+		$i = 0;
+		$password = "";
+		$max = strlen($chars) - 1;
+
+		while ($i < $length) {
+			$password .= $chars[mt_rand(0, $max)];
+			$i++;
+		}
+		return $password;
+	}
+
+}
+

+ 63 - 0
Test/Case/Model/TokenTest.php

@@ -0,0 +1,63 @@
+<?php
+
+App::import('Token', 'Tools.Model');
+App::uses('MyCakeTestCase', 'Tools.Lib');
+
+class TokenTest extends MyCakeTestCase {
+
+	public $Token = null;
+
+	public $fixtures = array('plugin.tools.token');
+
+	public function startTest() {
+		$this->Token = ClassRegistry::init('Tools.Token');
+	}
+
+	public function testTokenInstance() {
+		$this->assertTrue(is_a($this->Token, 'Token'));
+	}
+
+
+	public function testGenerateKey() {
+		$key = $this->Token->generateKey(4);
+		pr($key);
+		$this->assertTrue(!empty($key) && strlen($key) === 4);
+	}
+
+
+	public function testNewKeySpendKey() {
+		$key = $this->Token->newKey('test', null, null, 'xyz');
+		$this->assertTrue(!empty($key));
+
+		$res = $this->Token->useKey('test', $key);
+		pr($res);
+		$this->assertTrue(!empty($res));
+
+		$res = $this->Token->useKey('test', $key);
+		pr($res);
+		$this->assertTrue(!empty($res) && !empty($res['Token']['used']));
+
+		$res = $this->Token->useKey('test', $key.'x');
+		$this->assertFalse($res);
+
+		$res = $this->Token->useKey('testx', $key);
+		$this->assertFalse($res);
+	}
+
+	public function testGarbigeCollector() {
+		$data = array(
+			'created' => date(FORMAT_DB_DATETIME, time()-3*MONTH),
+			'type' => 'y',
+			'key' => 'x'
+		);
+		$this->Token->create();
+		$this->Token->save($data, false);
+		$count = $this->Token->find('count');
+		$this->Token->garbigeCollector();
+		$count2 = $this->Token->find('count');
+		$this->assertTrue($count > $count2);
+	}
+
+
+
+}

+ 135 - 0
Test/Fixture/TokenFixture.php

@@ -0,0 +1,135 @@
+<?php
+/* Token Fixture generated on: 2011-11-20 21:58:47 : 1321822727 */
+
+/**
+ * TokenFixture
+ *
+ */
+class TokenFixture extends CakeTestFixture {
+
+/**
+ * Fields
+ *
+ * @var array
+ */
+	public $fields = array(
+		'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary', 'collate' => NULL, 'comment' => ''),
+		'user_id' => array('type' => 'string', 'null' => false, 'length' => 36, 'collate' => 'utf8_unicode_ci', 'comment' => '', 'charset' => 'utf8'),
+		'type' => array('type' => 'string', 'null' => false, 'length' => 10, 'collate' => 'utf8_unicode_ci', 'comment' => 'e.g.:activate,reactivate', 'charset' => 'utf8'),
+		'key' => array('type' => 'string', 'null' => false, 'length' => 60, 'collate' => 'utf8_unicode_ci', 'comment' => '', 'charset' => 'utf8'),
+		'content' => array('type' => 'string', 'null' => false, 'collate' => 'utf8_unicode_ci', 'comment' => 'can transport some information', 'charset' => 'utf8'),
+		'used' => array('type' => 'boolean', 'null' => false, 'default' => '0', 'collate' => NULL, 'comment' => ''),
+		'created' => array('type' => 'datetime', 'null' => false, 'default' => NULL, 'collate' => NULL, 'comment' => ''),
+		'modified' => array('type' => 'datetime', 'null' => false, 'default' => NULL, 'collate' => NULL, 'comment' => ''),
+		'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)),
+		'tableParameters' => array()
+	);
+
+/**
+ * Records
+ *
+ * @var array
+ */
+	public $records = array(
+		array(
+			'id' => '77',
+			'user_id' => '1',
+			'type' => 'qlogin',
+			'key' => '7k8qdcizigtudvxn2v9zep',
+			'content' => 'i:1;',
+			'used' => 0,
+			'created' => '2011-08-02 18:00:41',
+			'modified' => '2011-08-02 18:00:41'
+		),
+		array(
+			'id' => '78',
+			'user_id' => '2',
+			'type' => 'qlogin',
+			'key' => '23e32tpkcmdn8x9j8n0n00',
+			'content' => 'i:2;',
+			'used' => 0,
+			'created' => '2011-08-02 18:00:41',
+			'modified' => '2011-08-02 18:00:41'
+		),
+		array(
+			'id' => '79',
+			'user_id' => '1',
+			'type' => 'qlogin',
+			'key' => '3mpzed7eoewsjvyvg4vy35',
+			'content' => 'a:3:{s:10:"controller";s:4:"test";s:6:"action";s:3:"foo";i:0;s:3:"bar";}',
+			'used' => 1,
+			'created' => '2011-08-02 18:00:41',
+			'modified' => '2011-08-02 18:00:41'
+		),
+		array(
+			'id' => '80',
+			'user_id' => '2',
+			'type' => 'qlogin',
+			'key' => 'af8ww4y7jxzq5n6npmjpxx',
+			'content' => 's:13:"/test/foo/bar";',
+			'used' => 1,
+			'created' => '2011-08-02 18:00:41',
+			'modified' => '2011-08-02 18:00:41'
+		),
+		array(
+			'id' => '81',
+			'user_id' => '1',
+			'type' => 'qlogin',
+			'key' => '2s7i3zjw0rn009j4no552b',
+			'content' => 'i:1;',
+			'used' => 0,
+			'created' => '2011-08-02 18:01:16',
+			'modified' => '2011-08-02 18:01:16'
+		),
+		array(
+			'id' => '82',
+			'user_id' => '2',
+			'type' => 'qlogin',
+			'key' => 'tro596dig63cay0ps09vre',
+			'content' => 'i:2;',
+			'used' => 0,
+			'created' => '2011-08-02 18:01:16',
+			'modified' => '2011-08-02 18:01:16'
+		),
+		array(
+			'id' => '83',
+			'user_id' => '1',
+			'type' => 'qlogin',
+			'key' => 'penfangwc40x550wwvgfmu',
+			'content' => 'a:3:{s:10:"controller";s:4:"test";s:6:"action";s:3:"foo";i:0;s:3:"bar";}',
+			'used' => 1,
+			'created' => '2011-08-02 18:01:16',
+			'modified' => '2011-08-02 18:01:16'
+		),
+		array(
+			'id' => '84',
+			'user_id' => '2',
+			'type' => 'qlogin',
+			'key' => '2y7m5srasm3ozej0izxbhe',
+			'content' => 's:13:"/test/foo/bar";',
+			'used' => 1,
+			'created' => '2011-08-02 18:01:16',
+			'modified' => '2011-08-02 18:01:16'
+		),
+		array(
+			'id' => '85',
+			'user_id' => '1',
+			'type' => 'qlogin',
+			'key' => '5c6dp2w54ynxii2xo3c50m',
+			'content' => 'i:1;',
+			'used' => 0,
+			'created' => '2011-08-02 18:01:54',
+			'modified' => '2011-08-02 18:01:54'
+		),
+		array(
+			'id' => '86',
+			'user_id' => '2',
+			'type' => 'qlogin',
+			'key' => 'fr6a0d4waue2v6hmqeyek5',
+			'content' => 'i:2;',
+			'used' => 0,
+			'created' => '2011-08-02 18:01:54',
+			'modified' => '2011-08-02 18:01:54'
+		),
+	);
+}