From 57e03505f8f91286b6e2559df2f81f7de1a0aeec Mon Sep 17 00:00:00 2001 From: Alex Rock Ancelet Date: Mon, 23 Sep 2024 14:49:01 +0200 Subject: [PATCH] Remove one usage of Html::displayErrorAndDie in Session::checkCSRF() --- .../Exception/Access/InvalidCsrfException.php | 58 +++++++++++++++++++ src/Session.php | 12 +--- 2 files changed, 60 insertions(+), 10 deletions(-) create mode 100644 src/Glpi/Exception/Access/InvalidCsrfException.php diff --git a/src/Glpi/Exception/Access/InvalidCsrfException.php b/src/Glpi/Exception/Access/InvalidCsrfException.php new file mode 100644 index 000000000000..bcaaaf11c12f --- /dev/null +++ b/src/Glpi/Exception/Access/InvalidCsrfException.php @@ -0,0 +1,58 @@ +. + * + * --------------------------------------------------------------------- + */ + +namespace Glpi\Exception\Access; + +use Symfony\Component\HttpFoundation\JsonResponse; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpFoundation\StreamedResponse; + +class InvalidCsrfException extends AccessException +{ + public function asResponse(): Response + { + $message = __("The action you have requested is not allowed."); + + $request = $this->getRequest(); + + // Output JSON if requested by client + if (str_contains($request->getAcceptableContentTypes()['HTTP_ACCEPT'] ?? '', 'application/json')) { + return new JsonResponse(['message' => $this->message], 403); + } + + return new StreamedResponse(function () use ($message) { + \Html::displayError($message, true); + }, 403); + } +} diff --git a/src/Session.php b/src/Session.php index d655722eeafc..186d422ca20a 100644 --- a/src/Session.php +++ b/src/Session.php @@ -33,10 +33,10 @@ * --------------------------------------------------------------------- */ -use Glpi\Application\View\TemplateRenderer; use Glpi\Cache\CacheManager; use Glpi\Cache\I18nCache; use Glpi\Event; +use Glpi\Exception\Access\InvalidCsrfException; use Glpi\Exception\Access\RequiresHttpsException; use Glpi\Exception\Access\SessionExpiredException; use Glpi\Plugin\Hooks; @@ -1782,15 +1782,7 @@ public static function checkCSRF($data) $user_id = self::getLoginUserID() ?? 'Anonymous'; Toolbox::logInFile('access-errors', "CSRF check failed for User ID: $user_id at $requested_url\n"); - $message = __("The action you have requested is not allowed."); - - // Output JSON if requested by client - if (strpos($_SERVER['HTTP_ACCEPT'] ?? '', 'application/json') !== false) { - http_response_code(403); - die(json_encode(["message" => $message])); - } - - Html::displayErrorAndDie($message, true); + throw new InvalidCsrfException(); } }