<?php declare(strict_types=1);
namespace BXK_FancyProtect\Subscriber;
use BXK_FancyProtect\Controller\BXK_FancyProtectController as Controller;
use Shopware\Administration\Controller\AdministrationController;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Storefront\Event\StorefrontRenderEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\Session;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Shopware\Core\Framework\Event\BeforeSendResponseEvent;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class BXK_FancyProtectSubscriber implements EventSubscriberInterface {
private $config;
private $router;
public function __construct(RouterInterface $router, SystemConfigService $systemConfigService) {
$this->config = $systemConfigService;
$this->router = $router;
}
public static function getSubscribedEvents(): array {
return [
BeforeSendResponseEvent::class => 'fancyResponseCheck'
];
}
public function fancyResponseCheck(BeforeSendResponseEvent $event){
$protectionUri = $this->router->generate("frontend.bxk_fancyprotect.entry");
$maintenanceUri = $this->router->generate("frontend.maintenance.page");
$request = $event->getRequest();
$key = $this->getProtectionPassword($request);
if (!isset($key) || $key == "") {
return; // no key setted -> allow!
}
$releaseDate = $this->getConfigValue('unlockTime', $request->attributes->get('sw-sales-channel-id'));
if (isset($releaseDate)) {
if (strtotime($releaseDate) <= strtotime('now')) {
return; // release date -> allow request
}
}
$cookie = $event->getRequest()->cookies->get("entry");
if(!is_null($cookie)){
$md5Key = $event->getRequest()->cookies->get("entry");
if (md5($this->getProtectionPassword($request)) == $md5Key) {
// Password in cookies is correct -> allow request
return;
}
}
$attributes = $request->attributes;
if(!$attributes->count()){
// not in storefront -> allow request
return;
}
$isProtectionPage = $event->getRequest()->getRequestUri() == $protectionUri;
$isMaintenancePage = $event->getRequest()->getRequestUri() == $maintenanceUri;
if($request->isXmlHttpRequest() || !$attributes->get("_is_sales_channel") || $isMaintenancePage || $isProtectionPage) {
// Ajax / XmlHttpRequest request (eg newsletter) or on protection page -> allow request
return;
}
$event->setResponse(
new RedirectResponse($protectionUri)
);
}
private function getProtectionPassword($request) {
return $this->getConfigValue('protectionPwd', $request->attributes->get('sw-sales-channel-id'));
}
private function getConfigValue($key, $default = null) {
$configKey = 'BXK_FancyProtect.config.' . $key;
return $this->config->get($configKey, $default);
}
}