80 lines
2.7 KiB
PHP
80 lines
2.7 KiB
PHP
<?php
|
|
|
|
namespace app\common\middleware;
|
|
|
|
use app\common\repositories\system\merchant\MerchantAdminRepository;
|
|
use app\common\repositories\system\merchant\MerchantRepository;
|
|
use app\Request;
|
|
use crmeb\exceptions\AuthException;
|
|
use crmeb\services\JwtTokenService;
|
|
use Firebase\JWT\ExpiredException;
|
|
use think\exception\ValidateException;
|
|
use think\Response;
|
|
use Throwable;
|
|
|
|
class ShopTokenMiddleware extends BaseMiddleware{
|
|
|
|
|
|
public function before(Request $request){
|
|
$force = $this->getArg(0, true);
|
|
try {
|
|
$token = trim($request->header('Shop-Token'));
|
|
if (strpos($token, 'Bearer') === 0) $token = trim(substr($token, 6));
|
|
if (!$token) throw new ValidateException('请登录');
|
|
/**
|
|
* @var MerchantAdminRepository $repository
|
|
*/
|
|
$repository = app()->make(MerchantAdminRepository::class);
|
|
$service = new JwtTokenService();
|
|
try {
|
|
$payload = $service->parseToken($token);
|
|
} catch (ExpiredException $e) {
|
|
$repository->checkToken($token);
|
|
$payload = $service->decode($token);
|
|
} catch (Throwable $e) {//Token 过期
|
|
throw new ValidateException('token 已过期');
|
|
}
|
|
if ('mer' != $payload->jti[1]) throw new ValidateException('无效的 token');
|
|
|
|
$admin = $repository->get($payload->jti[0]);
|
|
if (!$admin) throw new ValidateException('账号不存在');
|
|
if (!$admin['status']) throw new ValidateException('账号已被禁用');
|
|
|
|
/**
|
|
* @var MerchantRepository $merchantRepository
|
|
*/
|
|
$merchantRepository = app()->make(MerchantRepository::class);
|
|
|
|
$merchant = $merchantRepository->get($admin->mer_id);
|
|
|
|
if (!$merchant || !$merchant['status'])
|
|
throw new ValidateException('商户已被锁定');
|
|
|
|
} catch (Throwable $e) {
|
|
if ($force) throw $e;
|
|
$request->macro('shopIsLogin', function () {
|
|
return false;
|
|
});
|
|
$request->macros(['merchantType', 'shopMerId'], function () {
|
|
throw new ValidateException('请登录');
|
|
});
|
|
return;
|
|
}
|
|
$repository->updateToken($token);
|
|
|
|
$request->macro('shopIsLogin', function () {
|
|
return true;
|
|
});
|
|
$request->macro('merchantType', function () use (&$merchant) {
|
|
return $merchant->merchant_type;
|
|
});
|
|
$request->macro('merchantId', function () use (&$admin) {
|
|
return $admin->mer_id;
|
|
});
|
|
}
|
|
|
|
public function after(Response $response){
|
|
// TODO: Implement after() method.
|
|
}
|
|
}
|