HEX
Server: Apache
System: Linux srv13.cpanelhost.cl 3.10.0-962.3.2.lve1.5.38.el7.x86_64 #1 SMP Thu Jun 18 05:28:41 EDT 2020 x86_64
User: cca63905 (4205)
PHP: 7.3.20
Disabled: NONE
Upload Files
File: //proc/self/cwd/nueva/modules/wnetsecurity/controllers/admin/AdminWnetSecurityAjaxController.php
<?php
/**
 * Copyright since 2014 Waynet Sp. z o.o.
 * PrestaShop is an International Registered Trademark & Property of PrestaShop SA
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.md.
 * It is also available through the world-wide-web at this URL:
 * https://opensource.org/licenses/OSL-3.0
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to kontakt@waynet.pl so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to https://devdocs.prestashop-project.org/ for more information.
 *
 * @author    Waynet Sp. z o.o. <kontakt@waynet.pl>
 * @copyright since 2014 Waynet Sp. z o.o.
 * @license   https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
 */

declare(strict_types=1);

use Psr\Http\Client\NetworkExceptionInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Waynet\OAuth2\Client\Exception\RequestException;
use Waynet\Security\Api\ApiClient;
use Waynet\Security\Api\Exception\HydraException;
use Waynet\Security\Http\Exception\HttpException;
use Waynet\Security\Presenter\ReportPresenter;

class AdminWnetSecurityAjaxController extends \ModuleAdminController
{
    public const TAB_NAME = 'AdminWnetSecurityAjax';
    private const TRANSLATION_SOURCE = 'adminwnetsecurityajaxcontroller';

    /** @var WnetSecurity */
    public $module;

    private $apiClient;
    private $reportPresenter;

    public function __construct()
    {
        parent::__construct();

        $this->apiClient = $this->module->getService(ApiClient::class);
        $this->reportPresenter = $this->module->getService(ReportPresenter::class);
    }

    /** @return never-return */
    public function postProcess()
    {
        try {
            $response = parent::postProcess();

            if (!$response instanceof Response) {
                throw new NotFoundHttpException($this->module->l('Unsupported action', self::TRANSLATION_SOURCE));
            }
        } catch (\Exception $exception) {
            $response = $this->handleException($exception);
        }

        $response->send();

        exit;
    }

    public function ajaxProcessGetLastReport(): JsonResponse
    {
        if (!$this->access('view')) {
            throw new AccessDeniedHttpException($this->module->l('Access denied', self::TRANSLATION_SOURCE));
        }

        if (null === $report = $this->apiClient->getLastReport()) {
            return new JsonResponse(null, Response::HTTP_NOT_FOUND);
        }

        return new JsonResponse($this->reportPresenter->present($report));
    }

    public function ajaxProcessGetReports(): JsonResponse
    {
        if (!$this->access('view')) {
            throw new AccessDeniedHttpException($this->module->l('Access denied', self::TRANSLATION_SOURCE));
        }

        $page = (int) Tools::getValue('page', 1);
        if (0 >= $page) {
            throw new BadRequestHttpException($this->module->l('Malformed request', self::TRANSLATION_SOURCE));
        }

        $collectionPage = $this->apiClient
            ->getReports()
            ->getPage($page);

        return new JsonResponse($this->reportPresenter->presentCollectionPage($collectionPage));
    }

    public function ajaxProcessUpdateVulnerability(): JsonResponse
    {
        if (!$this->access('edit')) {
            throw new AccessDeniedHttpException($this->module->l('Access denied', self::TRANSLATION_SOURCE));
        }

        $payload = $this->getJsonPayload();
        if (
            !isset($payload['uri'], $payload['hidden'])
            || !is_string($payload['uri'])
            || !is_bool($payload['hidden'])
        ) {
            throw new BadRequestHttpException($this->module->l('Malformed request', self::TRANSLATION_SOURCE));
        }

        $this->apiClient->patch($payload['uri'], [
            'hidden' => $payload['hidden'],
        ]);

        return new JsonResponse(null, Response::HTTP_NO_CONTENT);
    }

    private function getJsonPayload(): array
    {
        $requestContents = \Tools::file_get_contents('php://input');
        $data = json_decode($requestContents, true);

        if (!is_array($data)) {
            throw new BadRequestHttpException($this->module->l('Malformed request', self::TRANSLATION_SOURCE));
        }

        return $data;
    }

    private function handleException(Exception $exception): JsonResponse
    {
        return new JsonResponse(
            ['error' => $this->getErrorMessageByException($exception)],
            $this->getResponseStatusCodeByException($exception),
            $exception instanceof HttpExceptionInterface ? $exception->getHeaders() : []
        );
    }

    private function getErrorMessageByException(Exception $exception): string
    {
        switch (true) {
            case $exception instanceof HttpExceptionInterface:
                return $exception->getMessage();
            case $exception instanceof NetworkExceptionInterface:
                return sprintf(
                    $this->module->l('Connection error: %s', self::TRANSLATION_SOURCE),
                    $exception->getMessage()
                );
            case $exception instanceof HydraException:
                return sprintf(
                    $this->module->l('API error: %s', self::TRANSLATION_SOURCE),
                    $exception->getMessage()
                );
            case $exception instanceof HttpException:
                $request = $exception->getRequest();

                return sprintf(
                    $this->module->l('Unsuccessful API response: %d for %s %s', self::TRANSLATION_SOURCE),
                    $exception->getCode(),
                    $request->getMethod(),
                    (string) $request->getUri()
                );
            case $exception instanceof RequestException:
                return sprintf(
                    $this->module->l('Authorization server error: %s', self::TRANSLATION_SOURCE),
                    $exception->getMessage()
                );
            default:
                return $this->module->l('Unexpected error', self::TRANSLATION_SOURCE);
        }
    }

    private function getResponseStatusCodeByException(Exception $exception): int
    {
        switch (true) {
            case $exception instanceof HttpExceptionInterface:
                return $exception->getStatusCode();
            case $exception instanceof HydraException:
            case $exception instanceof HttpException:
                return $exception->getCode();
            default:
                return Response::HTTP_INTERNAL_SERVER_ERROR;
        }
    }
}