Files
fdesk/app/middleware/AuthCheck.php
T
2025-07-18 17:32:42 +08:00

96 lines
3.8 KiB
PHP

<?php
namespace app\middleware;
use app\common\utils\Jwt;
use ReflectionClass;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
use app\common\service\BasicDataService;
class AuthCheck implements MiddlewareInterface
{
public function process(Request $request, callable $handler) : Response
{
$controller = new ReflectionClass($request->controller);
$properties = $controller->getDefaultProperties();
$noNeedLogin = $properties['noNeedLogin'] ?? [];
$noNeedAuth = $properties['noNeedAuth'] ?? [];
$noNeedHeaderData = $properties['noNeedHeaderData'] ?? [];
// header数据
if (!in_array($request->action, $noNeedHeaderData)) { //如果需要header数据
try {
$corpAbbr = $request->header('Fdesk-Corp-Abbr');
$systemCode = $request->header('Fdesk-System-Code');
$loginType = $request->header('Fdesk-Login-Type');
$basicDataService = new BasicDataService();
if ($basicDataService->checkAndCacheBaseParams($loginType, $systemCode, $corpAbbr)) {
$request->login_type = $loginType;
$request->system_code = $systemCode;
$request->corp_abbr = $corpAbbr;
$request->basic_data = [
'login_type' => $loginType,
'system_code' => $systemCode,
'corp_abbr' => $corpAbbr
];
}
return $handler($request);
} catch (\Throwable $th) {
throw $th;
$body = [
'status' => 'fail',
'code' => 401,
'message' => $th->getMessage(),
'data' => [],
];
return response(json_encode($body, JSON_UNESCAPED_UNICODE), 401, ['Content-Type' => 'application/json']);
}
}
// 不登陆&不鉴权
if (!in_array($request->action, $noNeedLogin)) { //如果需要登陆&鉴权
try {
$authHeader = $request->header('Fdesk-Auth-Token');
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);
return $handler($request);
} 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']);
}
}
// 登陆&不鉴权
// if (!in_array($request->action, $noNeedAuth)) { //如果需要登陆&不鉴权
// try {
// return $handler($request);
// } 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']);
// }
// }
return $handler($request);
}
}