| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- <?php
- declare(strict_types=1);
- namespace App\Middleware\Auth;
- use App\Model\User;
- use Hyperf\Di\Annotation\Inject;
- use Phper666\JWTAuth\Exception\TokenValidException;
- use Phper666\JWTAuth\JWT;
- use Phper666\JWTAuth\Util\JWTUtil;
- use Psr\Container\ContainerInterface;
- use Psr\Http\Message\ResponseInterface;
- use Psr\Http\Server\MiddlewareInterface;
- use Psr\Http\Message\ServerRequestInterface;
- use Psr\Http\Server\RequestHandlerInterface;
- class TokenMiddleware implements MiddlewareInterface
- {
- /**
- * @var ContainerInterface
- */
- protected $container;
- /**
- * @Inject()
- * @var JWT
- */
- protected $jwt;
- public function __construct(ContainerInterface $container)
- {
- $this->container = $container;
- }
- public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
- {
- try {
- // 根据具体业务判断逻辑走向,这里假设用户携带的token有效
- $token = $request->getHeaderLine('Authorization') ?? '';
- if (strlen($token) > 0) {
- $token = JWTUtil::handleToken($token);
- if ($token == false || !$this->jwt->checkToken($token)) {
- throw new TokenValidException(__('api.1005'), 401);
- }
- $authId = $token->getClaim('authId');
- $user = User::where('id', $authId)->where(['enable'=> 'T'])->first();
- if(!$user){
- throw new TokenValidException(__('api.1029'), 401);
- }
- }else{
- throw new TokenValidException(__('api.1010'), 401);
- }
- } catch (\Exception $exception){
- throw new TokenValidException(__('api.1006'), 401);
- }
- return $handler->handle($request);
- }
- }
|