102 lines
2.9 KiB
PHP
Executable File
102 lines
2.9 KiB
PHP
Executable File
<?php
|
|
|
|
declare(strict_types=1);
|
|
/**
|
|
* This file is part of the youyao/admin-api.
|
|
*
|
|
* (c) youyao <info@nuancebiotech.cn>
|
|
* This source file is subject to the license under the project that is bundled.
|
|
*/
|
|
namespace App\Middleware;
|
|
|
|
|
|
|
|
# 生成才能被自动注册
|
|
# composer dumpautoload 执行加载 不行在执行
|
|
# 生成中间件 php ./bin/hyperf.php gen:middleware Auth/FooMiddleware 【Auth = 文件夹名称-可以不带 默默人会生成在 app下的Middleware
|
|
# 文件夹中,若没有自动创建 /FooMiddleware = 中间价名称】
|
|
|
|
|
|
|
|
|
|
|
|
|
|
use App\Exception\BusinessException;
|
|
use App\Kernel\Jwt\Jwt;
|
|
use App\Logic\Company\CompanyLogic;
|
|
use App\Repository\Admin\UserRepository;
|
|
use Hyperf\HttpServer\Contract\RequestInterface;
|
|
use Hyperf\Utils\Arr;
|
|
use Hyperf\Utils\Context;
|
|
use Psr\Container\ContainerInterface;
|
|
use Psr\Http\Message\ResponseInterface;
|
|
use Psr\Http\Message\ServerRequestInterface;
|
|
use Psr\Http\Server\MiddlewareInterface;
|
|
use Psr\Http\Server\RequestHandlerInterface;
|
|
use Youyao\Framework\ErrCode;
|
|
use Youyao\Framework\Logger\LoggerApp;
|
|
|
|
class AuthMiddleware implements MiddlewareInterface
|
|
{
|
|
/**
|
|
* @var ContainerInterface
|
|
*/
|
|
protected $container;
|
|
|
|
/**
|
|
* @var Jwt
|
|
*/
|
|
private $jwt;
|
|
|
|
/**
|
|
* @var UserRepository
|
|
*/
|
|
private $user;
|
|
|
|
private $exclude = [
|
|
'/api/auth/login'
|
|
];
|
|
|
|
public function __construct(ContainerInterface $container)
|
|
{
|
|
$this->container = $container;
|
|
$this->jwt = $container->get(Jwt::class);
|
|
$this->user = $container->get(UserRepository::class);
|
|
}
|
|
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
|
|
{
|
|
if (in_array($request->getUri()->getPath(), $this->exclude)) {
|
|
return $handler->handle($request);
|
|
}
|
|
|
|
$req = $this->container->get(RequestInterface::class);
|
|
$token = $req->header('Authorization');
|
|
if (! $token) {
|
|
LoggerApp::error('未获取到 Authorization 头信息');
|
|
throw new BusinessException('认证失败', ErrCode::Unauthorized);
|
|
}
|
|
|
|
$payload = $this->jwt->decode(substr($token, 7));
|
|
$userId = Arr::get($payload, 'sub');
|
|
if (! $userId) {
|
|
LoggerApp::error('jwt 获取用户 id 失败');
|
|
throw new BusinessException('认证失败', ErrCode::Unauthorized);
|
|
}
|
|
|
|
$user = $this->user->getUserInfoById($userId);
|
|
if ($user->isForbidden()) {
|
|
throw new BusinessException('帐户已经被禁用,请联系管理员', ErrCode::Unauthorized);
|
|
}
|
|
|
|
if (!CompanyLogic::validateUserCompany($user)) {
|
|
throw new BusinessException('公司帐户已被禁用或不在服务期限内,请联系平台', ErrCode::Unauthorized);
|
|
}
|
|
|
|
Context::set('user', $user);
|
|
|
|
|
|
return $handler->handle($request);
|
|
}
|
|
}
|