|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file has been created by developers from BitBag. |
| 5 | + * Feel free to contact us once you face any issues or want to start |
| 6 | + * You can find more information about us on https://bitbag.io and write us |
| 7 | + * an email on hello@bitbag.io. |
| 8 | + */ |
| 9 | + |
| 10 | +declare(strict_types=1); |
| 11 | + |
| 12 | +namespace BitBag\SyliusUserComPlugin\Authenticator; |
| 13 | + |
| 14 | +use BitBag\SyliusUserComPlugin\Trait\UserComApiAwareInterface; |
| 15 | +use Psr\Log\LoggerInterface; |
| 16 | +use Sylius\Component\Channel\Context\ChannelContextInterface; |
| 17 | +use Symfony\Component\HttpFoundation\Request; |
| 18 | +use Symfony\Component\HttpFoundation\Response; |
| 19 | + |
| 20 | +final class RequestAuthenticator implements RequestAuthenticatorInterface |
| 21 | +{ |
| 22 | + public function __construct( |
| 23 | + private readonly ChannelContextInterface $channelContext, |
| 24 | + private readonly LoggerInterface $logger, |
| 25 | + ) { |
| 26 | + } |
| 27 | + |
| 28 | + public function authenticate(Request $request): bool |
| 29 | + { |
| 30 | + $channel = $this->channelContext->getChannel(); |
| 31 | + if (!$channel instanceof UserComApiAwareInterface) { |
| 32 | + return false; |
| 33 | + } |
| 34 | + |
| 35 | + $apiKey = $channel->getUserComApiKey(); |
| 36 | + $requestApiKey = $request->headers->get('X-User-Com-Signature'); |
| 37 | + if (null === $requestApiKey) { |
| 38 | + return false; |
| 39 | + } |
| 40 | + |
| 41 | + $content = $request->getContent(false); |
| 42 | + |
| 43 | + if (is_resource($content)) { |
| 44 | + $content = stream_get_contents($content); |
| 45 | + } |
| 46 | + |
| 47 | + if (!is_string($content)) { |
| 48 | + throw new \InvalidArgumentException('Invalid JSON payload', Response::HTTP_BAD_REQUEST); |
| 49 | + } |
| 50 | + |
| 51 | + $content = json_encode( |
| 52 | + json_decode($content, true), |
| 53 | + \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE, |
| 54 | + ); |
| 55 | + |
| 56 | + if (false === is_string($content)) { |
| 57 | + $this->logger->warning('User.com - Invalid JSON content.'); |
| 58 | + |
| 59 | + throw new \InvalidArgumentException('Invalid JSON content.'); |
| 60 | + } |
| 61 | + |
| 62 | + if (null === $apiKey) { |
| 63 | + $this->logger->warning('User.com - Missing API key.'); |
| 64 | + |
| 65 | + return false; |
| 66 | + } |
| 67 | + |
| 68 | + $signature = hash_hmac('sha256', $content, $apiKey); |
| 69 | + |
| 70 | + return hash_equals($signature, $requestApiKey); |
| 71 | + } |
| 72 | +} |
0 commit comments