From 740b4d952a521c511ab950769aff7913f11dd730 Mon Sep 17 00:00:00 2001 From: xiaochong0302 Date: Tue, 5 May 2020 17:32:50 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96csrf=5Ftoken?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Library/Security.php | 70 +++++++++++++++++++--------------------- 1 file changed, 34 insertions(+), 36 deletions(-) diff --git a/app/Library/Security.php b/app/Library/Security.php index fd7fe161..7b13b836 100644 --- a/app/Library/Security.php +++ b/app/Library/Security.php @@ -2,7 +2,7 @@ namespace App\Library; -use App\Library\Cache\Backend\Redis as RedisCache; +use Phalcon\Cache\Backend\Redis as RedisCache; use Phalcon\Di; use Phalcon\Session\Adapter\Redis as RedisSession; use Phalcon\Text; @@ -37,6 +37,38 @@ class Security $this->generateToken(); } + public function generateToken() + { + $this->tokenKey = $this->session->getId(); + + $key = $this->getCacheKey($this->tokenKey); + + $lifetime = $this->options['lifetime']; + + $content = [ + 'hash' => Text::random(Text::RANDOM_ALNUM, 32), + 'expire' => time() + $lifetime, + ]; + + $cacheContent = $this->cache->get($key); + + if ($cacheContent) { + $this->tokenValue = $cacheContent['hash']; + if ($cacheContent['expire'] < time() + $lifetime / 2) { + $this->cache->save($key, $content, $lifetime); + $this->tokenValue = $content['hash']; + } + } else { + $this->cache->save($key, $content, $lifetime); + $this->tokenValue = $content['hash']; + } + } + + protected function getCacheKey($tokenKey) + { + return "csrf_token:{$tokenKey}"; + } + public function getTokenKey() { return $this->tokenKey; @@ -47,49 +79,15 @@ class Security return $this->tokenValue; } - public function generateToken() - { - $this->tokenKey = $this->session->getId(); - - $key = $this->getCacheKey($this->tokenKey); - - $content = [ - 'hash' => Text::random(Text::RANDOM_ALNUM, 32), - 'time' => time(), - ]; - - $lifetime = $this->options['lifetime']; - - $cache = $this->cache->get($key); - - if ($cache) { - $this->tokenValue = $cache['hash']; - if (time() - $cache['time'] > $lifetime / 2) { - $this->cache->save($key, $content, $lifetime); - $this->tokenValue = $content['hash']; - } - } else { - $this->cache->save($key, $content, $lifetime); - $this->tokenValue = $content['hash']; - } - } - public function checkToken($tokenKey, $tokenValue) { $key = $this->getCacheKey($tokenKey); $content = $this->cache->get($key); - if (!$content) { - return false; - } + if (!$content) return false; return $tokenValue == $content['hash']; } - protected function getCacheKey($tokenKey) - { - return "csrf_token:{$tokenKey}"; - } - }