Files

50 lines
1.8 KiB
PHP
Raw Permalink Normal View History

2025-07-09 19:11:57 +08:00
<?php
namespace app\middleware;
use app\common\utils\Jwt;
use ReflectionClass;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
class AuthCheck implements MiddlewareInterface
{
public function process(Request $request, callable $handler) : Response
{
$controller = new ReflectionClass($request->controller);
2025-07-18 17:32:42 +08:00
$properties = $controller->getDefaultProperties();
$noNeedLogin = $properties['noNeedLogin'] ?? [];
$noNeedAuth = $properties['noNeedAuth'] ?? [];
2025-07-21 15:09:06 +08:00
if (in_array($request->action, $noNeedLogin)) {
// 白名单
return $handler($request);
} else {
2025-07-09 19:11:57 +08:00
try {
2025-07-11 15:21:00 +08:00
$authHeader = $request->header('Fdesk-Auth-Token');
2025-07-09 19:11:57 +08:00
if (!$authHeader || !preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
$body = [
'status' => 'fail',
'code' => 401,
'message' => '未授权',
'data' => [],
];
return response(json_encode($body, JSON_UNESCAPED_UNICODE), 401, ['Content-Type' => 'application/json']);
}
$token = $matches[1];
$request->user = (new Jwt())->verifyToken($token);
2025-07-18 17:32:42 +08:00
return $handler($request);
2025-07-09 19:11:57 +08:00
} catch (\Throwable $e) {
$body = [
'status' => 'fail',
'code' => 401,
'message' => $e->getMessage(),
'data' => [],
];
return response(json_encode($body, JSON_UNESCAPED_UNICODE), 401, ['Content-Type' => 'application/json']);
}
}
2025-07-18 17:32:42 +08:00
return $handler($request);
2025-07-09 19:11:57 +08:00
}
}