<?php
namespace Kaylo\Management\Subscriber;
use Kaylo\Management\Storefront\KayloController;
use League\OAuth2\Server\CryptKey;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class KayloKeySubscriber implements EventSubscriberInterface {
private CryptKey $privateKey;
private string $kayloKey;
public function __construct($privateKey, $kayloKey) {
if (!$privateKey instanceof CryptKey) {
$privateKey = new CryptKey($privateKey);
}
$this->privateKey = $privateKey;
$this->kayloKey = $kayloKey;
}
/**
* @throws Exception
*/
public function onKernelController(ControllerEvent $event) {
$controller = $event->getController();
// when a controller class defines multiple action methods, the controller
// is returned as [$controllerInstance, 'methodName']
if (is_array($controller)) {
$controller = array_shift($controller);
}
if ($controller instanceof KayloController) {
$encryptedKey = $event->getRequest()->get('key');
if (empty($encryptedKey)) {
throw new Exception('This action needs a Kaylo key');
}
if ($this->decryptKey($encryptedKey) !== $this->kayloKey) {
throw new Exception('This Kaylo key is invalid ');
}
}
}
private function decryptKey(string $encryptedMessage) {
$key = hex2bin($encryptedMessage);
$privateKey = openssl_pkey_get_private($this->privateKey->getKeyPath(), $this->privateKey->getPassPhrase());
openssl_private_decrypt(
$key,
$decryptedMessage,
$privateKey
);
return $decryptedMessage;
}
public static function getSubscribedEvents(): array {
return [
KernelEvents::CONTROLLER => 'onKernelController',
];
}
}