1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- <?php
- // +----------------------------------------------------------------------
- // | [ WE CAN DO IT MORE SIMPLE ]
- // +----------------------------------------------------------------------
- // | Copyright (c) 2018-2020 rights reserved.
- // +----------------------------------------------------------------------
- // | Author: TABLE ME
- // +----------------------------------------------------------------------
- // | Date: 2020-08-30 14:59
- // +----------------------------------------------------------------------
- namespace app\warehouse\middleware;
- use app\model\admin\Admin;
- use app\model\warehouse\Warehouse;
- use app\Request;
- use Firebase\JWT\ExpiredException;
- use Firebase\JWT\JWT;
- use library\exceptions\AuthException;
- use library\interfaces\MiddlewareInterface;
- use think\facade\Cache;
- use think\facade\Config;
- class AdminAuthTokenMiddleware implements MiddlewareInterface
- {
- public function handle(Request $request, \Closure $next)
- {
- $authInfo = null;
- $token = trim($request->header('WAREHOUSE-TOKEN'));
- $adminInfo = $this->adminParseToken($token);
- $request->adminInfo = $adminInfo;
- return $next($request);
- }
- /**
- * 获取Admin授权信息
- * @param $token
- * @param int $expires
- * @param string $prefix
- * @return array
- * @throws \Psr\SimpleCache\InvalidArgumentException
- */
- public static function adminParseToken($token): array
- {
- $redis = Cache::store('redis');
- try {
- if (!$token || !$redis->has($token) || !($cacheToken = $redis->get($token)))
- throw new AuthException('请重新登录', -91);
- [$adminInfo, $type] = Warehouse::parseToken($token);
- Cache::store('redis')->set($cacheToken['token'], $cacheToken, $cacheToken['exp']);
- } catch (ExpiredException $e) {
- list($headb64, $bodyb64, $cryptob64) = explode('.', $token);
- $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64));
- $type = $payload->jti->type;
- $adminInfo = Warehouse::where('id', $payload->jti->id)->find();
- if (!$adminInfo) {
- $redis->delete($token);
- throw new AuthException('登录超时,请重新登录!', -91);
- }
- $redis->set($cacheToken['token'], $cacheToken, $cacheToken['exp']);
- } catch (\Throwable $e) {
- $redis->delete($token);
- throw new AuthException('登录超时,请重新登录!', -91);
- } catch (\Throwable $e) {
- throw new AuthException('登录超时,请重新登录!', -91);
- }
- if (!isset($adminInfo) || !$adminInfo || !$adminInfo->id) {
- $redis->delete($token);
- throw new AuthException('登录超时,请重新登录!', -91);
- }
- $adminInfo->type = $type;
- return $adminInfo->toArray();
- }
- }
|