38 lines
1.1 KiB
PHP
38 lines
1.1 KiB
PHP
<?php
|
|
|
|
namespace app\api\middleware;
|
|
|
|
use app\common\exception\UnauthorizedException;
|
|
use app\common\model\user\User;
|
|
use Tinywan\Jwt\JwtToken;
|
|
use Webman\Http\Request;
|
|
use Webman\Http\Response;
|
|
use Webman\MiddlewareInterface;
|
|
|
|
class AuthMiddleware implements MiddlewareInterface
|
|
{
|
|
|
|
public function process(Request $request, callable $handler): Response
|
|
{
|
|
try {
|
|
$payload = JwtToken::verify();
|
|
if (!$payload) {
|
|
throw new UnauthorizedException('用户不存在', 401);
|
|
}
|
|
$request->user = User::withTrashed()->find($payload['extend']['id']);
|
|
if (empty($request->user)) {
|
|
throw new UnauthorizedException('用户不存在', 401);
|
|
}
|
|
} catch (\Throwable $e) {
|
|
$controller = new $request->controller;
|
|
if ((!isset($controller->optional) || !in_array($request->action, $controller->optional))) {
|
|
throw new UnauthorizedException('请登录', 401);
|
|
}
|
|
}
|
|
|
|
/** @var Response $response */
|
|
$response = $handler($request);
|
|
return $response;
|
|
}
|
|
}
|