50 lines
1.8 KiB
PHP
50 lines
1.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;
|
|
|
|
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'] ?? [];
|
|
|
|
if (in_array($request->action, $noNeedLogin)) {
|
|
// 白名单
|
|
return $handler($request);
|
|
} else {
|
|
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']);
|
|
}
|
|
}
|
|
|
|
return $handler($request);
|
|
}
|
|
} |