<?php
namespace Opentalent\OtCore\Middleware;

use Opentalent\OtAdmin\Http\ApiController;
use PHPUnit\Exception;
use TYPO3\CMS\Backend\Middleware\BackendUserAuthenticator;
use TYPO3\CMS\Backend\Routing\Route;

/**
 * Overrides (XClass) the core BackendUserAuthenticator middleware to extend
 * the public routes to the /otadmin/* routes (only for authorized Ips)
 *
 * @internal
 */
class OtBackendUserAuthenticator extends BackendUserAuthenticator
{
    /**
     * Check if the user is required for the request
     * If we're trying to do a login or an ajax login, don't require a user
     *
     * @param Route $route
     * @return bool whether the request can proceed without a login required
     */
    protected function isLoggedInBackendUserRequired(Route $route): bool
    {
        if (class_exists('\Opentalent\OtAdmin\Http\ApiController')) {
            // The routes defined in the ot-admin extension are limited to some ips
            if (preg_match('/\/otadmin\/.+/', $route->getPath())) {
                if (ApiController::isIpAllowed($_SERVER['REMOTE_ADDR'])) {
                    return false;
                } else {
                    throw new \RuntimeException('An unauthorized IP (' . $_SERVER['REMOTE_ADDR'] . ') ' .
                                                        'tried to run the following ot-admin command: ' . $_SERVER['QUERY_STRING']);
                }
            }
        }

        // The routes defined in the ot-core extension are public
        if (preg_match('/\/otcore\/.+/', $route->getPath())) {
            return false;
        }

        return parent::isLoggedInBackendUserRequired($route);
    }
}
