Files
MrleeAdmin/backend/app/middleware/ApiEncryptMiddleware.php
T
2026-08-31 11:33:59 +08:00

63 lines
1.7 KiB
PHP

<?php
declare(strict_types=1);
namespace app\middleware;
use core\tool\ApiEncryptService;
use core\tool\Json;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;
class ApiEncryptMiddleware implements MiddlewareInterface
{
public function __construct(protected ApiEncryptService $service)
{
}
public function process(Request $request, callable $handler): Response
{
if ($this->service->isEnabled()
&& !$this->service->shouldExcludePath($request->path())
&& $this->service->isEncryptedRequest($request)) {
try {
$data = $this->service->decryptRequest($request);
$this->service->applyDecryptedPayload($request, $data);
} catch (\Throwable $exception) {
return Json::fail($exception->getMessage(), null, 400);
}
}
$response = $handler($request);
if (!$response instanceof Response) {
return $response;
}
if (!$this->service->shouldEncrypt($request)) {
return $response;
}
if (!$this->service->hasActiveSessionKey()) {
return $response;
}
if (!$this->service->isJsonResponse($response)) {
return $response;
}
try {
$body = $response->rawBody();
if ($body === '') {
return $response;
}
$encryptedBody = $this->service->encryptResponseBody($body);
return $response->withBody($encryptedBody)->withHeader('Content-Type', 'application/json');
} catch (\Throwable $exception) {
return Json::fail($exception->getMessage(), null, 500);
}
}
}