From 0194292e846e5a154518d9d7d6078d9347109bf4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Folt=C3=BDn?= Date: Fri, 19 Jan 2024 09:36:26 +0100 Subject: [PATCH] =?UTF-8?q?Lazy=20vytvo=C5=99en=C3=AD=20kl=C3=AD=C4=8D?= =?UTF-8?q?=C5=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - je to celkem náročná operace - nevytváříme tak zbytečně klíče, když je AsymetricJwtTokenizer uvedený jako závislost, ale při aktuálním běhu aplikace ho nevyužijeme --- src/Tokenizer/AsymetricJwtTokenizer.php | 50 ++++++++++++++++++++++--- 1 file changed, 44 insertions(+), 6 deletions(-) diff --git a/src/Tokenizer/AsymetricJwtTokenizer.php b/src/Tokenizer/AsymetricJwtTokenizer.php index 9c04d2f..d39128c 100644 --- a/src/Tokenizer/AsymetricJwtTokenizer.php +++ b/src/Tokenizer/AsymetricJwtTokenizer.php @@ -9,38 +9,76 @@ final class AsymetricJwtTokenizer implements Tokenizer /** - * @var mixed + * @var \OpenSSLAsymmetricKey|resource */ private $privateKey; + private string $privateKeyFile; + /** - * @var mixed + * @var \OpenSSLAsymmetricKey|resource */ private $publicKey; + private string $publicKeyFile; + public function __construct( string $privateKey, string $publicKey ) { - $this->privateKey = \openssl_pkey_get_private('file://' . $privateKey); - $this->publicKey = \openssl_pkey_get_public('file://' . $publicKey); + $this->privateKeyFile = $privateKey; + $this->publicKeyFile= $publicKey; } public function create(\Pd\PublicAccess\PublicAccess $object): string { - return \Firebase\JWT\JWT::encode($object->jsonSerialize(), $this->privateKey, self::ALGORITHM); + return \Firebase\JWT\JWT::encode($object->jsonSerialize(), $this->privateKey(), self::ALGORITHM); } public function decode(string $token): \stdClass { /** @var \stdClass $decode */ - $decode = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key($this->publicKey, self::ALGORITHM)); + $decode = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key($this->publicKey(), self::ALGORITHM)); return $decode; } + + /** + * @return \OpenSSLAsymmetricKey|resource + */ + private function privateKey() + { + if ( ! isset($this->privateKey)) { + $this->privateKey = \openssl_pkey_get_private('file://' . $this->privateKeyFile); + + if ($this->privateKey === FALSE) { + throw new \RuntimeException('Invalid private key for JWT tokenizer'); + } + } + + return $this->privateKey; + } + + + /** + * @return \OpenSSLAsymmetricKey|resource + */ + private function publicKey() + { + if ( ! isset($this->publicKey)) { + $this->publicKey = \openssl_pkey_get_public('file://' . $this->publicKeyFile); + + if ($this->publicKey === FALSE) { + throw new \RuntimeException('Invalid public key for JWT tokenizer'); + } + } + + return $this->publicKey; + } + }