1
0
mirror of https://gitee.com/koogua/course-tencent-cloud.git synced 2025-08-05 22:11:40 +08:00

精简auth

This commit is contained in:
xiaochong0302 2020-04-07 19:32:00 +08:00
parent bcba85d0be
commit c0e38d68fd
53 changed files with 1013 additions and 922 deletions

View File

@ -1,35 +0,0 @@
<?php
namespace App\Caches;
use App\Repos\AccessToken as AccessTokenRepo;
class AccessToken extends Cache
{
protected $lifetime = 2 * 3600;
public function getLifetime()
{
return $this->lifetime;
}
public function getKey($id = null)
{
return "access_token:{$id}";
}
public function getContent($id = null)
{
$accessTokenRepo = new AccessTokenRepo();
$accessToken = $accessTokenRepo->findById($id);
if (!$accessToken) {
return new \stdClass();
}
return $accessToken;
}
}

View File

@ -3,16 +3,17 @@
namespace App\Http\Admin\Controllers; namespace App\Http\Admin\Controllers;
use App\Models\Audit as AuditModel; use App\Models\Audit as AuditModel;
use App\Services\AuthUser\Admin as AdminAuthUser; use App\Services\Auth\Admin as AdminAuth;
use App\Traits\Response as ResponseTrait; use App\Traits\Response as ResponseTrait;
use App\Traits\Security as SecurityTrait; use App\Traits\Security as SecurityTrait;
use Phalcon\Mvc\Dispatcher; use Phalcon\Mvc\Dispatcher;
use Yansongda\Supports\Collection;
class Controller extends \Phalcon\Mvc\Controller class Controller extends \Phalcon\Mvc\Controller
{ {
/** /**
* @var array * @var Collection
*/ */
protected $authUser; protected $authUser;
@ -112,11 +113,11 @@ class Controller extends \Phalcon\Mvc\Controller
protected function getAuthUser() protected function getAuthUser()
{ {
/** /**
* @var AdminAuthUser $authUser * @var AdminAuth $auth
*/ */
$authUser = $this->getDI()->get('auth'); $auth = $this->getDI()->get('auth');
return $authUser->getAuthInfo(); return $auth->getAuthInfo();
} }
} }

View File

@ -2,7 +2,7 @@
namespace App\Http\Admin; namespace App\Http\Admin;
use App\Services\AuthUser\Admin as AdminAuthUser; use App\Services\Auth\Admin as AdminAuth;
use Phalcon\DiInterface; use Phalcon\DiInterface;
use Phalcon\Mvc\ModuleDefinitionInterface; use Phalcon\Mvc\ModuleDefinitionInterface;
use Phalcon\Mvc\View; use Phalcon\Mvc\View;
@ -27,7 +27,7 @@ class Module implements ModuleDefinitionInterface
}); });
$di->setShared('auth', function () { $di->setShared('auth', function () {
return new AdminAuthUser(); return new AdminAuth();
}); });
} }

View File

@ -19,18 +19,14 @@ class AlipayTest extends PaymentTest
$qrcode = $alipayService->scan($trade); $qrcode = $alipayService->scan($trade);
$result = $qrcode ?: false; return $qrcode ?: false;
return $result;
} }
public function status($tradeNo) public function status($tradeNo)
{ {
$alipayService = new AlipayService(); $alipayService = new AlipayService();
$result = $alipayService->status($tradeNo); return $alipayService->status($tradeNo);
return $result;
} }
public function cancel($tradeNo) public function cancel($tradeNo)

View File

@ -2,7 +2,7 @@
namespace App\Http\Admin\Services; namespace App\Http\Admin\Services;
use App\Services\AuthUser\Admin as AdminAuthUser; use App\Services\Auth\Admin as AdminAuth;
use Phalcon\Mvc\User\Component; use Phalcon\Mvc\User\Component;
class AuthMenu extends Component class AuthMenu extends Component
@ -115,11 +115,11 @@ class AuthMenu extends Component
protected function getAuthInfo() protected function getAuthInfo()
{ {
/** /**
* @var AdminAuthUser $authUser * @var AdminAuth $auth
*/ */
$authUser = $this->getDI()->get('auth'); $auth = $this->getDI()->get('auth');
return $authUser->getAuthInfo(); return $auth->getAuthInfo();
} }
} }

View File

@ -4,6 +4,7 @@ namespace App\Http\Admin\Services;
use App\Models\Order as OrderModel; use App\Models\Order as OrderModel;
use App\Models\Trade as TradeModel; use App\Models\Trade as TradeModel;
use App\Services\Auth\Admin as AdminAuth;
abstract class PaymentTest extends Service abstract class PaymentTest extends Service
{ {
@ -21,15 +22,17 @@ abstract class PaymentTest extends Service
public function createOrder() public function createOrder()
{ {
/** /**
* @var object $authUser * @var AdminAuth $auth
*/ */
$authUser = $this->getDI()->get('auth')->getAuthInfo(); $auth = $this->getDI()->get('auth');
$authUser = $auth->getAuthInfo();
$order = new OrderModel(); $order = new OrderModel();
$order->subject = '测试 - 支付测试0.01元'; $order->subject = '测试 - 支付测试0.01元';
$order->amount = 0.01; $order->amount = 0.01;
$order->user_id = $authUser->id; $order->user_id = $authUser['id'];
$order->item_type = OrderModel::ITEM_TEST; $order->item_type = OrderModel::ITEM_TEST;
$order->create(); $order->create();

View File

@ -2,7 +2,7 @@
namespace App\Http\Admin\Services; namespace App\Http\Admin\Services;
use App\Services\AuthUser as AuthUserService; use App\Services\Auth as AuthService;
use App\Validators\Account as AccountValidator; use App\Validators\Account as AccountValidator;
use App\Validators\Security as SecurityValidator; use App\Validators\Security as SecurityValidator;
@ -10,7 +10,7 @@ class Session extends Service
{ {
/** /**
* @var AuthUserService * @var AuthService
*/ */
protected $auth; protected $auth;

View File

@ -16,27 +16,21 @@ class WxpayTest extends PaymentTest
$qrcode = $wxpayService->scan($trade); $qrcode = $wxpayService->scan($trade);
$result = $qrcode ?: false; return $qrcode ?: false;
return $result;
} }
public function status($tradeNo) public function status($tradeNo)
{ {
$wxpayService = new WxpayService(); $wxpayService = new WxpayService();
$result = $wxpayService->status($tradeNo); return $wxpayService->status($tradeNo);
return $result;
} }
public function cancel($tradeNo) public function cancel($tradeNo)
{ {
$wxpayService = new WxpayService(); $wxpayService = new WxpayService();
$response = $wxpayService->close($tradeNo); return $wxpayService->close($tradeNo);
return $response;
} }
} }

View File

@ -29,7 +29,7 @@
</ul> </ul>
<ul class="layui-nav layui-layout-right"> <ul class="layui-nav layui-layout-right">
<li class="layui-nav-item"> <li class="layui-nav-item">
<a href="javascript:">{{ auth_user['name'] }}</a> <a href="javascript:">{{ auth_user.name }}</a>
<dl class="layui-nav-child"> <dl class="layui-nav-child">
<dd><a target="content" href="#">基本资料</a></dd> <dd><a target="content" href="#">基本资料</a></dd>
<dd><a target="content" href="#">安全设置</a></dd> <dd><a target="content" href="#">安全设置</a></dd>

View File

@ -8,8 +8,7 @@
<table class="kg-table layui-table"> <table class="kg-table layui-table">
<tr> <tr>
<td colspan="10">订单编号:{{ order.sn }} <td colspan="6">订单编号:{{ order.sn }}</td>
<td>
<tr> <tr>
<tr> <tr>
<td>商品信息</td> <td>商品信息</td>

View File

@ -2,7 +2,7 @@
namespace App\Http\Api; namespace App\Http\Api;
use App\Services\AuthUser\Web as ApiAuthUser; use App\Services\Auth\Api as ApiAuth;
use Phalcon\DiInterface; use Phalcon\DiInterface;
use Phalcon\Mvc\ModuleDefinitionInterface; use Phalcon\Mvc\ModuleDefinitionInterface;
use Phalcon\Mvc\View; use Phalcon\Mvc\View;
@ -24,7 +24,7 @@ class Module implements ModuleDefinitionInterface
}); });
$di->setShared('auth', function () { $di->setShared('auth', function () {
return new ApiAuthUser(); return new ApiAuth();
}); });
} }

View File

@ -2,7 +2,7 @@
namespace App\Http\Api\Services; namespace App\Http\Api\Services;
use App\Services\AuthUser\Api as ApiAuthUser; use App\Services\Auth\Api as ApiAuth;
use App\Validators\Account as AccountValidator; use App\Validators\Account as AccountValidator;
class Login extends Service class Login extends Service
@ -14,9 +14,9 @@ class Login extends Service
$user = $validator->checkUserLogin($name, $password); $user = $validator->checkUserLogin($name, $password);
$authUser = new ApiAuthUser(); $auth = new ApiAuth();
return $authUser->saveAuthInfo($user); return $auth->saveAuthInfo($user);
} }
public function loginByVerify($name, $code) public function loginByVerify($name, $code)
@ -25,9 +25,9 @@ class Login extends Service
$user = $validator->checkVerifyLogin($name, $code); $user = $validator->checkVerifyLogin($name, $code);
$authUser = new ApiAuthUser(); $auth = new ApiAuth();
return $authUser->saveAuthInfo($user); return $auth->saveAuthInfo($user);
} }
} }

View File

@ -2,16 +2,16 @@
namespace App\Http\Api\Services; namespace App\Http\Api\Services;
use App\Services\AuthUser\Api as ApiAuthUser; use App\Services\Auth\Api as ApiAuth;
class Logout extends Service class Logout extends Service
{ {
public function logout() public function logout()
{ {
$authUser = new ApiAuthUser(); $auth = new ApiAuth();
return $authUser->clearAuthInfo(); return $auth->clearAuthInfo();
} }
} }

View File

@ -2,7 +2,7 @@
namespace App\Http\Html5; namespace App\Http\Html5;
use App\Services\AuthUser\Html5 as Html5AuthUser; use App\Services\Auth\Html5 as Html5Auth;
use Phalcon\DiInterface; use Phalcon\DiInterface;
use Phalcon\Mvc\ModuleDefinitionInterface; use Phalcon\Mvc\ModuleDefinitionInterface;
use Phalcon\Mvc\View; use Phalcon\Mvc\View;
@ -24,7 +24,7 @@ class Module implements ModuleDefinitionInterface
}); });
$di->setShared('auth', function () { $di->setShared('auth', function () {
return new Html5AuthUser(); return new Html5Auth();
}); });
} }

View File

@ -2,8 +2,9 @@
namespace App\Http\Web\Controllers; namespace App\Http\Web\Controllers;
use App\Caches\Config as ConfigCache;
use App\Caches\NavTreeList as NavTreeListCache; use App\Caches\NavTreeList as NavTreeListCache;
use App\Caches\SectionConfig as SectionConfigCache;
use App\Services\Auth\Web as WebAuth;
use App\Traits\Response as ResponseTrait; use App\Traits\Response as ResponseTrait;
use App\Traits\Security as SecurityTrait; use App\Traits\Security as SecurityTrait;
use Phalcon\Mvc\Dispatcher; use Phalcon\Mvc\Dispatcher;
@ -46,6 +47,9 @@ class Controller extends \Phalcon\Mvc\Controller
protected function getAuthUser() protected function getAuthUser()
{ {
/**
* @var WebAuth $auth
*/
$auth = $this->getDI()->get('auth'); $auth = $this->getDI()->get('auth');
return $auth->getAuthInfo(); return $auth->getAuthInfo();
@ -53,16 +57,16 @@ class Controller extends \Phalcon\Mvc\Controller
protected function getNavList() protected function getNavList()
{ {
$cache = new NavTreeListCache(); $treeListCache = new NavTreeListCache();
return $cache->get(); return $treeListCache->get();
} }
protected function getSiteConfig() protected function getSiteConfig()
{ {
$cache = new ConfigCache(); $sectionCache = new SectionConfigCache();
return $cache->getSectionConfig('site'); return $sectionCache->get('site');
} }
} }

View File

@ -2,7 +2,7 @@
namespace App\Http\Web; namespace App\Http\Web;
use App\Services\AuthUser\Web as WebAuthUser; use App\Services\Auth\Web as WebAuth;
use Phalcon\DiInterface; use Phalcon\DiInterface;
use Phalcon\Mvc\ModuleDefinitionInterface; use Phalcon\Mvc\ModuleDefinitionInterface;
use Phalcon\Mvc\View; use Phalcon\Mvc\View;
@ -27,7 +27,7 @@ class Module implements ModuleDefinitionInterface
}); });
$di->setShared('auth', function () { $di->setShared('auth', function () {
return new WebAuthUser(); return new WebAuth();
}); });
} }

View File

@ -1 +1 @@
<img src="/qrcode/img?text=http://ctc.koogua.com"> <img src="/qr/img?text=http://ctc.koogua.com">

View File

@ -9,7 +9,7 @@ class Password
public static function salt() public static function salt()
{ {
return Text::random(); return Text::random(Text::RANDOM_ALNUM, 8);
} }
public static function hash($password, $salt) public static function hash($password, $salt)

View File

@ -2,8 +2,6 @@
namespace App\Models; namespace App\Models;
use App\Caches\AccessToken as AccessTokenCache;
class AccessToken extends Model class AccessToken extends Model
{ {
@ -57,9 +55,7 @@ class AccessToken extends Model
public function beforeCreate() public function beforeCreate()
{ {
$this->id = $this->getRandId($this->user_id); $this->id = $this->getRandId($this->user_id);
$this->expiry_time = strtotime('+2 hours'); $this->expiry_time = strtotime('+2 hours');
$this->create_time = time(); $this->create_time = time();
} }
@ -68,13 +64,6 @@ class AccessToken extends Model
$this->update_time = time(); $this->update_time = time();
} }
public function afterCreate()
{
$accessTokenCache = new AccessTokenCache();
$accessTokenCache->rebuild($this->id);
}
protected function getRandId($userId, $prefix = 'AT') protected function getRandId($userId, $prefix = 'AT')
{ {
return md5("{$prefix}-{$userId}" . time() . rand(1000, 9999)); return md5("{$prefix}-{$userId}" . time() . rand(1000, 9999));

View File

@ -84,18 +84,14 @@ class Account extends Model
public function beforeCreate() public function beforeCreate()
{ {
$this->salt = Password::salt(); $this->salt = Password::salt();
$this->password = Password::hash($this->password, $this->salt); $this->password = Password::hash($this->password, $this->salt);
$this->create_time = time(); $this->create_time = time();
} }
public function beforeUpdate() public function beforeUpdate()
{ {
if (!empty($this->password)) { if (!empty($this->password)) {
$this->salt = Password::salt(); $this->salt = Password::salt();
$this->password = Password::hash($this->password, $this->salt); $this->password = Password::hash($this->password, $this->salt);
} }
@ -105,10 +101,8 @@ class Account extends Model
public function afterCreate() public function afterCreate()
{ {
$user = new User(); $user = new User();
$user->id = $this->id; $user->id = $this->id;
$user->name = "user_{$this->id}"; $user->name = "user_{$this->id}";
$user->create(); $user->create();
} }

View File

@ -133,16 +133,13 @@ class Category extends Model
public function rebuildCache() public function rebuildCache()
{ {
$cache = new CategoryCache(); $itemCache = new CategoryCache();
$itemCache->rebuild($this->id);
$cache->rebuild($this->id);
$listCache = new CategoryListCache(); $listCache = new CategoryListCache();
$listCache->rebuild(); $listCache->rebuild();
$treeListCache = new CategoryTreeListCache(); $treeListCache = new CategoryTreeListCache();
$treeListCache->rebuild(); $treeListCache->rebuild();
} }

View File

@ -243,16 +243,16 @@ class Chapter extends Model
switch ($course->model) { switch ($course->model) {
case Course::MODEL_VOD: case Course::MODEL_VOD:
$model = new ChapterVod(); $chapterVod = new ChapterVod();
$model->create($data); $chapterVod->create($data);
break; break;
case Course::MODEL_LIVE: case Course::MODEL_LIVE:
$model = new ChapterLive(); $chapterLive = new ChapterLive();
$model->create($data); $chapterLive->create($data);
break; break;
case Course::MODEL_READ: case Course::MODEL_READ:
$model = new ChapterRead(); $chapterRead = new ChapterRead();
$model->create($data); $chapterRead->create($data);
break; break;
} }
} }

View File

@ -77,12 +77,10 @@ class ChapterRead extends Model
public static function formatTypes() public static function formatTypes()
{ {
$list = [ return [
self::FORMAT_HTML => 'html', self::FORMAT_HTML => 'html',
self::FORMAT_MARKDOWN => 'format', self::FORMAT_MARKDOWN => 'markdown',
]; ];
return $list;
} }
} }

View File

@ -263,7 +263,6 @@ class Course extends Model
public function afterFetch() public function afterFetch()
{ {
$this->market_price = (float)$this->market_price; $this->market_price = (float)$this->market_price;
$this->vip_price = (float)$this->vip_price; $this->vip_price = (float)$this->vip_price;
if (!empty($this->attrs)) { if (!empty($this->attrs)) {

View File

@ -157,9 +157,8 @@ class Nav extends Model
public function rebuildCache() public function rebuildCache()
{ {
$cache = new NavTreeListCache(); $treeListCache = new NavTreeListCache();
$treeListCache->rebuild();
$cache->rebuild();
} }
public static function positionTypes() public static function positionTypes()

View File

@ -149,9 +149,7 @@ class Order extends Model
public function beforeCreate() public function beforeCreate()
{ {
$this->status = self::STATUS_PENDING; $this->status = self::STATUS_PENDING;
$this->sn = date('YmdHis') . rand(1000, 9999); $this->sn = date('YmdHis') . rand(1000, 9999);
$this->create_time = time(); $this->create_time = time();
if (!empty($this->item_info)) { if (!empty($this->item_info)) {

View File

@ -55,9 +55,7 @@ class RefreshToken extends Model
public function beforeCreate() public function beforeCreate()
{ {
$this->id = $this->getRandId($this->user_id); $this->id = $this->getRandId($this->user_id);
$this->expiry_time = strtotime('+30 days'); $this->expiry_time = strtotime('+30 days');
$this->create_time = time(); $this->create_time = time();
} }
@ -70,4 +68,5 @@ class RefreshToken extends Model
{ {
return md5("{$prefix}-{$userId}" . time() . rand(1000, 9999)); return md5("{$prefix}-{$userId}" . time() . rand(1000, 9999));
} }
} }

View File

@ -128,9 +128,7 @@ class Refund extends Model
public function beforeCreate() public function beforeCreate()
{ {
$this->status = self::STATUS_PENDING; $this->status = self::STATUS_PENDING;
$this->sn = date('YmdHis') . rand(1000, 9999); $this->sn = date('YmdHis') . rand(1000, 9999);
$this->create_time = time(); $this->create_time = time();
} }

View File

@ -131,8 +131,8 @@ class Slide extends Model
public function rebuildCache() public function rebuildCache()
{ {
$slideListCache = new SlideListCache(); $listCache = new SlideListCache();
$slideListCache->rebuild(); $listCache->rebuild();
} }
public static function targetTypes() public static function targetTypes()

View File

@ -125,9 +125,7 @@ class Trade extends Model
public function beforeCreate() public function beforeCreate()
{ {
$this->status = self::STATUS_PENDING; $this->status = self::STATUS_PENDING;
$this->sn = date('YmdHis') . rand(1000, 9999); $this->sn = date('YmdHis') . rand(1000, 9999);
$this->create_time = time(); $this->create_time = time();
} }

View File

@ -177,7 +177,6 @@ class User extends Model
public function afterCreate() public function afterCreate()
{ {
$maxUserIdCache = new MaxUserIdCache(); $maxUserIdCache = new MaxUserIdCache();
$maxUserIdCache->rebuild(); $maxUserIdCache->rebuild();
} }

View File

@ -28,7 +28,7 @@ class Router extends Provider
foreach ($webFiles as $file) { foreach ($webFiles as $file) {
if (strpos($file, 'Controller.php')) { if (strpos($file, 'Controller.php')) {
$className = str_replace('Controller.php', '', $file); $className = str_replace('Controller.php', '', $file);
$router->addModuleResource('home', 'App\Http\Web\Controllers\\' . $className); $router->addModuleResource('web', 'App\Http\Web\Controllers\\' . $className);
} }
} }

View File

@ -19,7 +19,7 @@ class Session extends Provider
'host' => $config->redis->host, 'host' => $config->redis->host,
'port' => $config->redis->port, 'port' => $config->redis->port,
'auth' => $config->redis->auth, 'auth' => $config->redis->auth,
'index' => $config->session->index, 'index' => $config->redis->index,
'prefix' => $config->session->prefix, 'prefix' => $config->session->prefix,
'lifetime' => $config->session->lifetime, 'lifetime' => $config->session->lifetime,
'persistent' => $config->redis->persistent, 'persistent' => $config->redis->persistent,

View File

@ -4,7 +4,7 @@ namespace App\Services;
use App\Models\User as UserModel; use App\Models\User as UserModel;
abstract class AuthUser extends Service abstract class Auth extends Service
{ {
abstract function saveAuthInfo(UserModel $user); abstract function saveAuthInfo(UserModel $user);

View File

@ -1,20 +1,16 @@
<?php <?php
namespace App\Services\AuthUser; namespace App\Services\Auth;
use App\Models\Role as RoleModel; use App\Models\Role as RoleModel;
use App\Models\User as UserModel; use App\Models\User as UserModel;
use App\Repos\Role as RoleRepo; use App\Repos\Role as RoleRepo;
use App\Services\AuthUser; use App\Services\Auth as AuthService;
use Yansongda\Supports\Collection;
class Admin extends AuthUser class Admin extends AuthService
{ {
/**
* 写入会话
*
* @param UserModel $user
*/
public function saveAuthInfo(UserModel $user) public function saveAuthInfo(UserModel $user)
{ {
$roleRepo = new RoleRepo(); $roleRepo = new RoleRepo();
@ -26,7 +22,6 @@ class Admin extends AuthUser
$authInfo = [ $authInfo = [
'id' => $user->id, 'id' => $user->id,
'name' => $user->name, 'name' => $user->name,
'avatar' => $user->avatar,
'routes' => $role->routes, 'routes' => $role->routes,
'root' => $root, 'root' => $root,
]; ];
@ -36,9 +31,6 @@ class Admin extends AuthUser
$this->session->set($authKey, $authInfo); $this->session->set($authKey, $authInfo);
} }
/**
* 清除会话
*/
public function clearAuthInfo() public function clearAuthInfo()
{ {
$authKey = $this->getAuthKey(); $authKey = $this->getAuthKey();
@ -46,43 +38,31 @@ class Admin extends AuthUser
$this->session->remove($authKey); $this->session->remove($authKey);
} }
/**
* 读取会话
*
* @return mixed
*/
public function getAuthInfo() public function getAuthInfo()
{ {
$authKey = $this->getAuthKey(); $authKey = $this->getAuthKey();
return $this->session->get($authKey); $authInfo = $this->session->get($authKey);
$items = $authInfo ? $authInfo : [];
return new Collection($items);
} }
/**
* 获取会话键值
*
* @return string
*/
public function getAuthKey() public function getAuthKey()
{ {
return 'admin_user_info'; return 'admin_auth_info';
} }
/**
* 判断权限
*
* @param string $route
* @return bool
*/
public function hasPermission($route) public function hasPermission($route)
{ {
$authUser = $this->getAuthInfo(); $authUser = $this->getAuthInfo();
if ($authUser->root) { if ($authUser['root']) {
return true; return true;
} }
if (in_array($route, $authUser->routes)) { if (in_array($route, $authUser['routes'])) {
return true; return true;
} }

89
app/Services/Auth/Api.php Normal file
View File

@ -0,0 +1,89 @@
<?php
namespace App\Services\Auth;
use App\Library\Cache\Backend\Redis as RedisCache;
use App\Models\AccessToken as AccessTokenModel;
use App\Models\RefreshToken as RefreshTokenModel;
use App\Models\User as UserModel;
use App\Services\Auth as AuthService;
use Yansongda\Supports\Collection;
class Api extends AuthService
{
public function saveAuthInfo(UserModel $user)
{
$accessToken = new AccessTokenModel();
$accessToken->user_id = $user->id;
$accessToken->create();
$refreshToken = new RefreshTokenModel();
$refreshToken->user_id = $user->id;
$refreshToken->create();
$authInfo = [
'id' => $user->id,
'name' => $user->name,
];
$cache = $this->getCache();
$key = $this->getCacheKey($accessToken->id);
$cache->save($key, $authInfo, 2 * 3600);
return new Collection([
'access_token' => $accessToken->id,
'refresh_token' => $refreshToken->id,
'expiry_time' => $accessToken->expiry_time,
]);
}
public function clearAuthInfo()
{
$authToken = $this->getAuthToken();
$cache = $this->getCache();
$key = $this->getCacheKey($authToken);
$cache->delete($key);
}
public function getAuthInfo()
{
$authToken = $this->getAuthToken();
if (!$authToken) return null;
$cache = $this->getCache();
$key = $this->getCacheKey($authToken);
$authInfo = $cache->get($key);
$items = $authInfo ? $authInfo : [];
return new Collection($items);
}
protected function getAuthToken()
{
return $this->request->getHeader('Authorization');
}
protected function getCacheKey($token)
{
return "access_token:{$token}";
}
/**
* @return RedisCache
*/
protected function getCache()
{
return $this->getDI()->get('cache');
}
}

View File

@ -0,0 +1,47 @@
<?php
namespace App\Services\Auth;
use App\Models\User as UserModel;
use App\Services\Auth as AuthService;
use Yansongda\Supports\Collection;
class Html5 extends AuthService
{
public function saveAuthInfo(UserModel $user)
{
$authKey = $this->getAuthKey();
$authInfo = [
'id' => $user->id,
'name' => $user->name,
];
$this->session->set($authKey, $authInfo);
}
public function clearAuthInfo()
{
$authKey = $this->getAuthKey();
$this->session->remove($authKey);
}
public function getAuthInfo()
{
$authKey = $this->getAuthKey();
$authInfo = $this->session->get($authKey);
$items = $authInfo ? $authInfo : [];
return new Collection($items);
}
public function getAuthKey()
{
return 'html5_auth_info';
}
}

View File

@ -1,11 +1,12 @@
<?php <?php
namespace App\Services\AuthUser; namespace App\Services\Auth;
use App\Models\User as UserModel; use App\Models\User as UserModel;
use App\Services\AuthUser; use App\Services\Auth as AuthService;
use Yansongda\Supports\Collection;
class Web extends AuthUser class Web extends AuthService
{ {
/** /**
@ -17,15 +18,12 @@ class Web extends AuthUser
{ {
$authKey = $this->getAuthKey(); $authKey = $this->getAuthKey();
$authUser = new \stdClass(); $authInfo = new Collection([
'id' => $user->id,
'name' => $user->name,
]);
$authUser->id = $user->id; $this->session->set($authKey, $authInfo);
$authUser->name = $user->name;
$authUser->avatar = $user->avatar;
$authUser->admin_role = $user->admin_role;
$authUser->edu_role = $user->edu_role;
$this->session->set($authKey, $authUser);
} }
/** /**
@ -41,13 +39,17 @@ class Web extends AuthUser
/** /**
* 读取会话 * 读取会话
* *
* @return mixed * @return Collection
*/ */
public function getAuthInfo() public function getAuthInfo()
{ {
$authKey = $this->getAuthKey(); $authKey = $this->getAuthKey();
return $this->session->get($authKey); $authInfo = $this->session->get($authKey);
$items = $authInfo ? $authInfo : [];
return new Collection($items);
} }
/** /**
@ -57,7 +59,7 @@ class Web extends AuthUser
*/ */
public function getAuthKey() public function getAuthKey()
{ {
return 'web_user_info'; return 'web_auth_info';
} }
} }

View File

@ -1,64 +0,0 @@
<?php
namespace App\Services\AuthUser;
use App\Caches\AccessToken as AccessTokenCache;
use App\Models\AccessToken as AccessTokenModel;
use App\Models\RefreshToken as RefreshTokenModel;
use App\Models\User as UserModel;
use App\Services\AuthUser;
class Api extends AuthUser
{
public function saveAuthInfo(UserModel $user)
{
$accessToken = new AccessTokenModel();
$accessToken->user_id = $user->id;
$accessToken->create();
$refreshToken = new RefreshTokenModel();
$refreshToken->user_id = $user->id;
$refreshToken->create();
return [
'access_token' => $accessToken->id,
'refresh_token' => $refreshToken->id,
'expiry_time' => $accessToken->expiry_time,
];
}
public function clearAuthInfo()
{
$authToken = $this->getAuthToken();
$accessTokenCache = new AccessTokenCache();
/**
* @var AccessTokenModel $accessToken
*/
$accessToken = $accessTokenCache->get($authToken);
if ($accessToken) {
$accessToken->update(['revoked' => 1]);
$accessTokenCache->delete($authToken);
}
}
public function getAuthInfo()
{
$authToken = $this->getAuthToken();
$accessTokenCache = new AccessTokenCache();
return $accessTokenCache->get($authToken);
}
public function getAuthToken()
{
return $this->request->getHeader('Authorization');
}
}

View File

@ -1,63 +0,0 @@
<?php
namespace App\Services\AuthUser;
use App\Models\User as UserModel;
use App\Services\AuthUser;
class Html5 extends AuthUser
{
/**
* 写入会话
*
* @param UserModel $user
*/
public function saveAuthInfo(UserModel $user)
{
$authKey = $this->getAuthKey();
$authUser = new \stdClass();
$authUser->id = $user->id;
$authUser->name = $user->name;
$authUser->avatar = $user->avatar;
$authUser->admin_role = $user->admin_role;
$authUser->edu_role = $user->edu_role;
$this->session->set($authKey, $authUser);
}
/**
* 清除会话
*/
public function clearAuthInfo()
{
$authKey = $this->getAuthKey();
$this->session->remove($authKey);
}
/**
* 读取会话
*
* @return mixed
*/
public function getAuthInfo()
{
$authKey = $this->getAuthKey();
return $this->session->get($authKey);
}
/**
* 获取会话键值
*
* @return string
*/
public function getAuthKey()
{
return 'html5_user_info';
}
}

View File

@ -15,7 +15,7 @@ class PasswordReset extends Service
$accountValidator = new AccountValidator(); $accountValidator = new AccountValidator();
$account = $accountValidator->checkLoginAccount($post['account']); $account = $accountValidator->checkLoginName($post['account']);
$accountValidator->checkPassword($post['new_password']); $accountValidator->checkPassword($post['new_password']);

View File

@ -10,7 +10,7 @@ use App\Validators\Security as SecurityValidator;
class Register extends Service class Register extends Service
{ {
public function register() public function registerByPhone()
{ {
$post = $this->request->getPost(); $post = $this->request->getPost();
@ -34,4 +34,28 @@ class Register extends Service
return $account; return $account;
} }
public function registerByEmail()
{
$post = $this->request->getPost();
$securityValidator = new SecurityValidator();
$securityValidator->checkVerifyCode($post['email'], $post['verify_code']);
$accountValidator = new AccountValidator();
$data = [];
$data['email'] = $accountValidator->checkEmail($post['email']);
$data['password'] = $accountValidator->checkPassword($post['password']);
$accountValidator->checkIfEmailTaken($post['email']);
$account = new AccountModel();
$account->create($data);
return $account;
}
} }

View File

@ -4,6 +4,7 @@ namespace App\Services\Frontend;
use App\Models\User as UserModel; use App\Models\User as UserModel;
use App\Repos\User as UserRepo; use App\Repos\User as UserRepo;
use App\Services\Auth as AuthService;
use App\Validators\Validator as AppValidator; use App\Validators\Validator as AppValidator;
use Phalcon\Mvc\User\Component; use Phalcon\Mvc\User\Component;
@ -11,15 +12,6 @@ class Service extends Component
{ {
public function getCurrentUser() public function getCurrentUser()
{
$userRepo = new UserRepo();
$user = $userRepo->findById(100015);
return $user;
}
public function getCurrentUser2()
{ {
$authUser = $this->getAuthUser(); $authUser = $this->getAuthUser();
@ -29,21 +21,10 @@ class Service extends Component
$userRepo = new UserRepo(); $userRepo = new UserRepo();
$user = $userRepo->findById($authUser->id); return $userRepo->findById($authUser['id']);
return $user;
} }
public function getLoginUser() public function getLoginUser()
{
$userRepo = new UserRepo();
$user = $userRepo->findById(100015);
return $user;
}
public function getLoginUser2()
{ {
$authUser = $this->getAuthUser(); $authUser = $this->getAuthUser();
@ -51,15 +32,18 @@ class Service extends Component
$validator->checkAuthUser($authUser); $validator->checkAuthUser($authUser);
dd($authUser);
$userRepo = new UserRepo(); $userRepo = new UserRepo();
$user = $userRepo->findById($authUser->id); return $userRepo->findById($authUser['id']);
return $user;
} }
public function getAuthUser() public function getAuthUser()
{ {
/**
* @var AuthService $auth
*/
$auth = $this->getDI()->get('auth'); $auth = $this->getDI()->get('auth');
return $auth->getAuthInfo(); return $auth->getAuthInfo();

View File

@ -41,6 +41,8 @@ class VerifyCode extends Service
$code = Text::random(Text::RANDOM_NUMERIC, 6); $code = Text::random(Text::RANDOM_NUMERIC, 6);
$this->cache->save($key, $code, $lifetime); $this->cache->save($key, $code, $lifetime);
return $code;
} }
public function getMailCode($email, $lifetime = 300) public function getMailCode($email, $lifetime = 300)
@ -50,6 +52,8 @@ class VerifyCode extends Service
$code = Text::random(Text::RANDOM_NUMERIC, 6); $code = Text::random(Text::RANDOM_NUMERIC, 6);
$this->cache->save($key, $code, $lifetime); $this->cache->save($key, $code, $lifetime);
return $code;
} }
public function checkSmsCode($phone, $code) public function checkSmsCode($phone, $code)

View File

@ -4,7 +4,7 @@ namespace App\Traits;
use App\Models\User as UserModel; use App\Models\User as UserModel;
use App\Repos\User as UserRepo; use App\Repos\User as UserRepo;
use App\Services\AuthUser as AuthUserService; use App\Services\Auth as AuthService;
use App\Validators\Validator as AppValidator; use App\Validators\Validator as AppValidator;
use Phalcon\Di; use Phalcon\Di;
@ -50,7 +50,7 @@ trait Auth
public function getAuthUser() public function getAuthUser()
{ {
/** /**
* @var AuthUserService $auth * @var AuthService $auth
*/ */
$auth = Di::getDefault()->get('auth'); $auth = Di::getDefault()->get('auth');

View File

@ -6,6 +6,7 @@ use App\Exceptions\BadRequest as BadRequestException;
use App\Exceptions\Forbidden as ForbiddenException; use App\Exceptions\Forbidden as ForbiddenException;
use App\Library\Util\Password as PasswordUtil; use App\Library\Util\Password as PasswordUtil;
use App\Library\Validator\Common as CommonValidator; use App\Library\Validator\Common as CommonValidator;
use App\Models\Account as AccountModel;
use App\Repos\Account as AccountRepo; use App\Repos\Account as AccountRepo;
use App\Repos\User as UserRepo; use App\Repos\User as UserRepo;
@ -39,6 +40,15 @@ class Account extends Validator
return $password; return $password;
} }
public function checkOriginPassword(AccountModel $account, $password)
{
$hash = PasswordUtil::hash($password, $account->salt);
if ($hash != $account->password) {
throw new BadRequestException('account.origin_password_incorrect');
}
}
public function checkIfPhoneTaken($phone) public function checkIfPhoneTaken($phone)
{ {
$accountRepo = new AccountRepo(); $accountRepo = new AccountRepo();
@ -61,7 +71,7 @@ class Account extends Validator
} }
} }
public function checkLoginAccount($name) public function checkLoginName($name)
{ {
$accountRepo = new AccountRepo(); $accountRepo = new AccountRepo();
@ -74,28 +84,19 @@ class Account extends Validator
} }
if (!$account) { if (!$account) {
throw new BadRequestException('account.not_found'); throw new BadRequestException('account.login_name_incorrect');
} }
return $account; return $account;
} }
public function checkOriginPassword($account, $password)
{
$hash = PasswordUtil::hash($password, $account->salt);
if ($hash != $account->password) {
throw new BadRequestException('account.origin_password_incorrect');
}
}
public function checkVerifyLogin($name, $code) public function checkVerifyLogin($name, $code)
{ {
$security = new Security(); $security = new Security();
$security->checkVerifyCode($name, $code); $security->checkVerifyCode($name, $code);
$account = $this->checkLoginAccount($name); $account = $this->checkLoginName($name);
$userRepo = new UserRepo(); $userRepo = new UserRepo();
@ -104,19 +105,7 @@ class Account extends Validator
public function checkUserLogin($name, $password) public function checkUserLogin($name, $password)
{ {
$accountRepo = new AccountRepo(); $account = $this->checkLoginName($name);
$account = null;
if (CommonValidator::email($name)) {
$account = $accountRepo->findByEmail($name);
} elseif (CommonValidator::phone($name)) {
$account = $accountRepo->findByPhone($name);
}
if (!$account) {
throw new BadRequestException('account.login_account_incorrect');
}
$hash = PasswordUtil::hash($password, $account->salt); $hash = PasswordUtil::hash($password, $account->salt);

View File

@ -9,6 +9,7 @@ use App\Library\Validator\Common as CommonValidator;
use App\Models\User as UserModel; use App\Models\User as UserModel;
use App\Repos\Role as RoleRepo; use App\Repos\Role as RoleRepo;
use App\Repos\User as UserRepo; use App\Repos\User as UserRepo;
use App\Services\Auth\Admin as AdminAuth;
class User extends Validator class User extends Validator
{ {
@ -181,11 +182,15 @@ class User extends Validator
public function checkIfCanEditUser($user) public function checkIfCanEditUser($user)
{ {
/**
* @var AdminAuth $auth
*/
$auth = $this->getDI()->get('auth'); $auth = $this->getDI()->get('auth');
$authUser = $auth->getAuthInfo(); $authUser = $auth->getAuthInfo();
if ($authUser->id) { if ($authUser['id']) {
} }
} }

View File

@ -9,18 +9,9 @@ use Phalcon\Mvc\User\Component;
class Validator extends Component class Validator extends Component
{ {
public function checkAuthToken($token)
{
if (!$token) {
throw new UnauthorizedException('sys.invalid_auth_token');
}
return $token;
}
public function checkAuthUser($user) public function checkAuthUser($user)
{ {
if (!$user) { if (empty($user['id'])) {
throw new UnauthorizedException('sys.auth_user_failed'); throw new UnauthorizedException('sys.auth_user_failed');
} }

View File

@ -104,7 +104,7 @@ class HttpKernel extends Kernel
'className' => 'App\Http\Web\Module', 'className' => 'App\Http\Web\Module',
'path' => app_path('Http/Web/Module.php'), 'path' => app_path('Http/Web/Module.php'),
], ],
'mobile' => [ 'html5' => [
'className' => 'App\Http\Html5\Module', 'className' => 'App\Http\Html5\Module',
'path' => app_path('Http/Html5/Module.php'), 'path' => app_path('Http/Html5/Module.php'),
], ],

View File

@ -9,6 +9,7 @@
"swiftmailer/swiftmailer": "^6.0", "swiftmailer/swiftmailer": "^6.0",
"peppeocchi/php-cron-scheduler": "^2.4", "peppeocchi/php-cron-scheduler": "^2.4",
"yansongda/pay": "^2.8", "yansongda/pay": "^2.8",
"yansongda/supports": "^2.0",
"tencentcloud/tencentcloud-sdk-php": "3.*", "tencentcloud/tencentcloud-sdk-php": "3.*",
"qcloudsms/qcloudsms_php": "0.1.*", "qcloudsms/qcloudsms_php": "0.1.*",
"qcloud/cos-sdk-v5": "2.*", "qcloud/cos-sdk-v5": "2.*",

1251
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -95,18 +95,13 @@ $config['redis']['lifetime'] = 7 * 86400;
/** /**
* 会话键前缀 * 会话键前缀
*/ */
$config['session']['prefix'] = ''; $config['session']['prefix'] = ':session:';
/** /**
* 会话有效期(秒) * 会话有效期(秒)
*/ */
$config['session']['lifetime'] = 2 * 3600; $config['session']['lifetime'] = 2 * 3600;
/**
* redis库编号
*/
$config['session']['index'] = 1;
/** /**
* 日志级别 * 日志级别
*/ */

View File

@ -22,7 +22,7 @@ $error['security.invalid_verify_code'] = '无效的验证码';
*/ */
$error['account.not_found'] = '账号不存在'; $error['account.not_found'] = '账号不存在';
$error['account.login_locked'] = '账号被锁定,无法登录'; $error['account.login_locked'] = '账号被锁定,无法登录';
$error['account.login_account_incorrect'] = '登录账号不正确'; $error['account.login_name_incorrect'] = '登录账号不正确';
$error['account.login_password_incorrect'] = '登录密码不正确'; $error['account.login_password_incorrect'] = '登录密码不正确';
$error['account.invalid_email'] = '无效的电子邮箱'; $error['account.invalid_email'] = '无效的电子邮箱';
$error['account.invalid_phone'] = '无效的手机号'; $error['account.invalid_phone'] = '无效的手机号';