This commit is contained in:
77
app/Middleware/CheckTokenMiddleware.php
Normal file
77
app/Middleware/CheckTokenMiddleware.php
Normal file
@ -0,0 +1,77 @@
|
||||
<?php
|
||||
/**
|
||||
* Author: ykxiao
|
||||
* Date: 2025/6/4
|
||||
* Time: 下午2:40
|
||||
* Description:
|
||||
*
|
||||
* (c) ykxiao <yk_9001@hotmail.com>
|
||||
*
|
||||
* This source file is subject to the MIT license that is bundled
|
||||
* with this source code in the file LICENSE.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Middleware;
|
||||
|
||||
use App\Context\UserContext;
|
||||
use App\Exception\ApiException;
|
||||
use App\JsonRpc\UserAuthServiceInterface;
|
||||
use App\Repository\Company\FirstCompanyRepository;
|
||||
use Exception;
|
||||
use Hyperf\Di\Annotation\Inject;
|
||||
use Psr\Container\ContainerInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Psr\Http\Server\MiddlewareInterface;
|
||||
use Psr\Http\Server\RequestHandlerInterface;
|
||||
|
||||
/**
|
||||
* Author: ykxiao
|
||||
* Date: 2025/6/4
|
||||
* Time: 下午2:43
|
||||
* Description: 验证Token中间件.
|
||||
*
|
||||
* (c) ykxiao <yk_9001@hotmail.com>
|
||||
*
|
||||
* This source file is subject to the MIT license that is bundled
|
||||
* with this source code in the file LICENSE.
|
||||
*/
|
||||
class CheckTokenMiddleware implements MiddlewareInterface
|
||||
{
|
||||
#[Inject]
|
||||
protected UserAuthServiceInterface $userAuthServiceInterface;
|
||||
|
||||
public function __construct(protected ContainerInterface $container)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
|
||||
{
|
||||
$token = $this->extractToken($request);
|
||||
|
||||
$rpcResult = $this->userAuthServiceInterface->userInfoByToken(['token' => $token]);
|
||||
|
||||
$userInfo = $rpcResult['result']['user'] ?? [];
|
||||
if (!$userInfo) {
|
||||
throw new ApiException('用户信息不存在', 401);
|
||||
}
|
||||
|
||||
UserContext::setCurrentUser($userInfo);
|
||||
|
||||
return $handler->handle($request);
|
||||
}
|
||||
|
||||
protected function extractToken(ServerRequestInterface $request): string
|
||||
{
|
||||
$authorizationHeader = $request->getHeaderLine('Authorization') ?? '';
|
||||
if (!$authorizationHeader) {
|
||||
throw new ApiException('授权标头无效', 401);
|
||||
}
|
||||
return str_starts_with($authorizationHeader, 'Bearer ') ? substr($authorizationHeader, 7) : '';
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user