44use Cake \Chronos \Chronos ;
55use Cake \Database \Schema \TableSchema ;
66use Cake \ORM \Table ;
7- use Cake \Utility \Text ;
7+ use Cake \Utility \Security ;
88
99class TokensTable extends Table
1010{
@@ -13,7 +13,7 @@ class TokensTable extends Table
1313 */
1414 protected function _initializeSchema (TableSchema $ schema )
1515 {
16- $ schema ->columnType ('content ' , 'json ' );
16+ $ schema ->setColumnType ('content ' , 'json ' );
1717
1818 return $ schema ;
1919 }
@@ -24,10 +24,10 @@ protected function _initializeSchema(TableSchema $schema)
2424 public function initialize (array $ config )
2525 {
2626 parent ::initialize ($ config );
27- $ this ->setTable ('token_tokens ' );
28- $ this ->setPrimaryKey ('id ' );
2927
30- $ this ->addBehavior ('Timestamp ' );
28+ $ this ->setTable ('token_tokens ' )
29+ ->setPrimaryKey ('id ' )
30+ ->addBehavior ('Timestamp ' );
3131 }
3232
3333 /**
@@ -56,7 +56,7 @@ public function read($id)
5656 public function newToken (array $ content = [], $ expire = null )
5757 {
5858 $ entity = $ this ->newEntity ([
59- 'id ' => $ this ->uniqId (),
59+ 'id ' => $ this ->_uniqId (),
6060 'content ' => $ content ,
6161 'expire ' => is_null ($ expire ) ? Chronos::parse ('+1 day ' ) : Chronos::parse ($ expire ),
6262 ]);
@@ -70,25 +70,24 @@ public function newToken(array $content = [], $expire = null)
7070 * generate uniq token id
7171 * @return string
7272 */
73- protected function uniqId ()
73+ protected function _uniqId ()
7474 {
7575 $ exists = true ;
7676
77- while ($ exists ) {
78- $ key = $ this ->generateKey ();
79- $ exists = $ this ->find ()->where (['id ' => $ key ])->first ();
80- }
77+ $ length = 8 ;
8178
82- return $ key ;
83- }
79+ do {
80+ // generate random
81+ $ random = base64_encode (Security::randomBytes ($ length * 4 ));
8482
85- /**
86- * generate random key
87- * @return string 8 chars key
88- */
89- protected function generateKey ()
90- {
91- return substr (hash ('sha256 ' , Text::uuid ()), 0 , 8 );
83+ // cleanup
84+ $ clean = preg_replace ('/[^A-Za-z0-9]/ ' , '' , $ random );
85+
86+ // random part length
87+ $ key = substr ($ clean , random_int (1 , $ length * 2 ), $ length );
88+ } while ($ this ->exists (['id ' => $ key ]));
89+
90+ return $ key ;
9291 }
9392
9493 /**
0 commit comments