<?php
namespace Opentalent\OtAdmin\Middleware;

use Opentalent\OtAdmin\Http\ApiController;
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
    {
        $isOtAdminRoute = (bool)preg_match('/\/otadmin\/.+/', $routePath);
        $ipAllowed = ApiController::isIpAllowed($_SERVER['REMOTE_ADDR']);
        if ($isOtAdminRoute) {
            if ($ipAllowed) {
                return true;
            } else {
                throw new \RuntimeException('An unauthorized IP (' . $_SERVER['REMOTE_ADDR'] . ') ' .
                                                    'tried to run the following ot-admin command: ' . $_SERVER['QUERY_STRING']);
            }
        }
        return parent::isLoggedInBackendUserRequired($routePath);
    }
}
