12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- <?php
- namespace app\http\middleware;
- use app\admin\model\system\SystemAdmin;
- use app\models\system\SystemStore;
- use app\models\system\SystemStoreArea;
- use app\models\user\User;
- use app\models\user\UserToken;
- use app\Request;
- use crmeb\exceptions\AuthException;
- use crmeb\interfaces\MiddlewareInterface;
- use crmeb\repositories\UserRepository;
- use think\db\exception\DataNotFoundException;
- use think\db\exception\ModelNotFoundException;
- use think\exception\DbException;
- /**
- * token验证中间件
- * Class AuthTokenMiddleware
- * @package app\http\middleware
- */
- class AuthTokenMiddleware implements MiddlewareInterface
- {
- public function handle(Request $request, \Closure $next, bool $force = true)
- {
- $request->filter(['htmlspecialchars', 'strip_tags', 'addslashes', 'trim']);
- $authInfo = null;
- // var_dump($request->action());
- // var_dump($request->controller());
- $token = trim(ltrim($request->header('Authori-zation'), 'Bearer'));
- $store_id = $request->header('store-id', 0);
- $location = $request->header('LatLon', '0,0');
- if (!$token) $token = trim(ltrim($request->header('Authorization'), 'Bearer'));//正式版,删除此行,某些服务器无法获取到token调整为 Authori-zation
- try {
- $authInfo = UserRepository::parseToken($token);
- $authInfo['user']['store_info'] = [];
- if ($authInfo['user']->admin_id) {
- $adminInfo = SystemAdmin::get($authInfo['user']->admin_id);
- if (!$adminInfo || !$adminInfo['status']) {
- $adminInfo = [];
- } else {
- $adminInfo = $adminInfo->toArray();
- if (in_array(sys_config('default_store_admin', 7), explode(',', $adminInfo['roles']))) {
- $authInfo['user']['store_info'] = SystemStore::verificWhere()->where('id', $adminInfo['store_id'])->find();
- }
- // $adminInfo['auth'] = $adminInfo['level'] === 0 ? SystemRole::getAllAuth() : SystemRole::rolesByAuth($adminInfo['roles']);
- }
- } else {
- $adminInfo = [];
- }
- } catch (AuthException $e) {
- if ($force)
- return app('json')->make($e->getCode(), $e->getMessage());
- }
- if (!is_null($authInfo)) {
- Request::macro('user', function () use (&$authInfo) {
- return $authInfo['user'];
- });
- Request::macro('tokenData', function () use (&$authInfo) {
- return $authInfo['tokenData'];
- });
- }
- Request::macro('location', function () use ($location) {
- return $location;
- });
- Request::macro('isLogin', function () use (&$authInfo) {
- return !is_null($authInfo);
- });
- Request::macro('admin_info', function () use (&$adminInfo) {
- return $adminInfo;
- });
- Request::macro('store_id', function () use (&$store_id) {
- return $store_id;
- });
- Request::macro('uid', function () use (&$authInfo) {
- return is_null($authInfo) ? 0 : $authInfo['user']->uid;
- });
- return $next($request);
- }
- }
|