<?php
namespace Opentalent\OtCore\Middleware;

use PHPUnit\Exception;
use TYPO3\CMS\Backend\Middleware\BackendUserAuthenticator;

/**
 * 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 string $routePath the Route path to check against
     * @return bool whether the request can proceed without a login required
     */
    protected function isLoggedInBackendUserRequired(string $routePath): 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\/.+/', $routePath)) {
                if (\Opentalent\OtAdmin\Http\ApiController::isIpAllowed($_SERVER['REMOTE_ADDR'])) {
                    return true;
                } 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\/.+/', $routePath)) {
            return true;
        }

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