Skip to content

Commit

Permalink
Respect allow send as guest configuration in resolver
Browse files Browse the repository at this point in the history
Resolver throws `GraphQlAuthorizationException` when sending as guest if allow
send as guest is disabled.

Fixes magento#732
  • Loading branch information
pmclain committed Jun 8, 2019
1 parent 9473b31 commit 63762d6
Show file tree
Hide file tree
Showing 4 changed files with 177 additions and 22 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,22 @@

namespace Magento\SendFriendGraphQl\Model\Resolver;

use Magento\Authorization\Model\UserContextInterface;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\DataObjectFactory;
use Magento\Framework\Event\ManagerInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlAuthorizationException;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\SendFriend\Model\SendFriend;
use Magento\SendFriend\Model\SendFriendFactory;
use Magento\SendFriend\Helper\Data as SendFriendHelper;

/**
* @inheritdoc
Expand All @@ -45,29 +49,41 @@ class SendEmailToFriend implements ResolverInterface
*/
private $eventManager;

/**
* @var SendFriendHelper
*/
private $sendFriendHelper;

/**
* @param SendFriendFactory $sendFriendFactory
* @param ProductRepositoryInterface $productRepository
* @param DataObjectFactory $dataObjectFactory
* @param ManagerInterface $eventManager
* @param SendFriendHelper|null $sendFriendHelper
*/
public function __construct(
SendFriendFactory $sendFriendFactory,
ProductRepositoryInterface $productRepository,
DataObjectFactory $dataObjectFactory,
ManagerInterface $eventManager
ManagerInterface $eventManager,
SendFriendHelper $sendFriendHelper = null
) {
$this->sendFriendFactory = $sendFriendFactory;
$this->productRepository = $productRepository;
$this->dataObjectFactory = $dataObjectFactory;
$this->eventManager = $eventManager;
$this->sendFriendHelper = $sendFriendHelper ?? ObjectManager::getInstance()->get(SendFriendHelper::class);
}

/**
* @inheritdoc
*/
public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
{
if (!$this->sendFriendHelper->isAllowForGuest() && $this->isUserGuest($context->getUserId(), $context->getUserType())) {
throw new GraphQlAuthorizationException(__('The current customer isn\'t authorized.'));
}

/** @var SendFriend $sendFriend */
$sendFriend = $this->sendFriendFactory->create();

Expand Down Expand Up @@ -195,4 +211,19 @@ private function extractSenderData(array $args): array
],
];
}

/**
* Checking if current customer is guest
*
* @param int|null $customerId
* @param int|null $customerType
* @return bool
*/
private function isUserGuest(?int $customerId, ?int $customerType): bool
{
if (null === $customerId || null === $customerType) {
return true;
}
return 0 === (int)$customerId || (int)$customerType === UserContextInterface::USER_TYPE_GUEST;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
namespace Magento\GraphQl\SendFriend;

use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\SendFriend\Model\SendFriend;
use Magento\SendFriend\Model\SendFriendFactory;
use Magento\TestFramework\Helper\Bootstrap;
Expand All @@ -23,21 +25,29 @@ class SendFriendTest extends GraphQlAbstract
* @var SendFriendFactory
*/
private $sendFriendFactory;

/**
* @var ProductRepositoryInterface
*/
private $productRepository;

/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;

protected function setUp()
{
$this->sendFriendFactory = Bootstrap::getObjectManager()->get(SendFriendFactory::class);
$this->productRepository = Bootstrap::getObjectManager()->get(ProductRepositoryInterface::class);
$this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class);
}

/**
* @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php
* @magentoApiDataFixture Magento/GraphQl/SendFriend/_files/enable_send_friend_guest.php
*/
public function testSendFriend()
public function testSendFriendGuestEnable()
{
$productId = (int)$this->productRepository->get('simple_product')->getId();
$recipients = '{
Expand All @@ -51,15 +61,57 @@ public function testSendFriend()
$query = $this->getQuery($productId, $recipients);

$response = $this->graphQlMutation($query);
self::assertEquals('Name', $response['sendEmailToFriend']['sender']['name']);
self::assertEquals('[email protected]', $response['sendEmailToFriend']['sender']['email']);
self::assertEquals('Lorem Ipsum', $response['sendEmailToFriend']['sender']['message']);
self::assertEquals('Recipient Name 1', $response['sendEmailToFriend']['recipients'][0]['name']);
self::assertEquals('[email protected]', $response['sendEmailToFriend']['recipients'][0]['email']);
self::assertEquals('Recipient Name 2', $response['sendEmailToFriend']['recipients'][1]['name']);
self::assertEquals('[email protected]', $response['sendEmailToFriend']['recipients'][1]['email']);
$this->assertResponse($response);
}

/**
* @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php
* @magentoApiDataFixture Magento/GraphQl/SendFriend/_files/disable_send_friend_guest.php
* @expectedException \Exception
* @expectedExceptionMessage The current customer isn't authorized.
*/
public function testSendFriendGuestDisableAsGuest()
{
$productId = (int)$this->productRepository->get('simple_product')->getId();
$recipients = '{
name: "Recipient Name 1"
email:"[email protected]"
},
{
name: "Recipient Name 2"
email:"[email protected]"
}';
$query = $this->getQuery($productId, $recipients);

$response = $this->graphQlMutation($query);
$this->assertResponse($response);
}

/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php
* @magentoApiDataFixture Magento/GraphQl/SendFriend/_files/disable_send_friend_guest.php
*/
public function testSendFriendGuestDisableAsCustomer()
{
$productId = (int)$this->productRepository->get('simple_product')->getId();
$recipients = '{
name: "Recipient Name 1"
email:"[email protected]"
},
{
name: "Recipient Name 2"
email:"[email protected]"
}';
$query = $this->getQuery($productId, $recipients);

$response = $this->graphQlMutation($query, [], '', $this->getHeaderMap());
$this->assertResponse($response);
}

/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testSendWithoutExistProduct()
{
$productId = 2018;
Expand All @@ -77,10 +129,11 @@ public function testSendWithoutExistProduct()
$this->expectExceptionMessage(
'The product that was requested doesn\'t exist. Verify the product and try again.'
);
$this->graphQlMutation($query);
$this->graphQlMutation($query, [], '', $this->getHeaderMap());
}

/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php
*/
public function testMaxSendEmailToFriend()
Expand Down Expand Up @@ -118,10 +171,11 @@ public function testMaxSendEmailToFriend()

$this->expectException(\Exception::class);
$this->expectExceptionMessage("No more than {$sendFriend->getMaxRecipients()} emails can be sent at a time.");
$this->graphQlMutation($query);
$this->graphQlMutation($query, [], '', $this->getHeaderMap());
}

/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
* @dataProvider sendFriendsErrorsDataProvider
* @param string $input
Expand Down Expand Up @@ -151,10 +205,11 @@ public function testErrors(string $input, string $errorMessage)
QUERY;
$this->expectException(\Exception::class);
$this->expectExceptionMessage($errorMessage);
$this->graphQlMutation($query);
$this->graphQlMutation($query, [], '', $this->getHeaderMap());
}

/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php
* TODO: use magentoApiConfigFixture (to be merged https://github.com/magento/graphql-ce/pull/351)
* @magentoApiDataFixture Magento/SendFriend/Fixtures/sendfriend_configuration.php
Expand Down Expand Up @@ -183,11 +238,12 @@ public function testLimitMessagesPerHour()

$maxSendToFriends = $sendFriend->getMaxSendsToFriend();
for ($i = 0; $i <= $maxSendToFriends + 1; $i++) {
$this->graphQlMutation($query);
$this->graphQlMutation($query, [], '', $this->getHeaderMap());
}
}

/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php
*/
public function testSendProductWithoutSenderEmail()
Expand All @@ -201,10 +257,11 @@ public function testSendProductWithoutSenderEmail()

$this->expectException(\Exception::class);
$this->expectExceptionMessage('GraphQL response contains errors: Please provide Email for all of recipients.');
$this->graphQlMutation($query);
$this->graphQlMutation($query, [], '', $this->getHeaderMap());
}

/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product_without_visibility.php
*/
public function testSendProductWithoutVisibility()
Expand All @@ -220,14 +277,8 @@ public function testSendProductWithoutVisibility()
}';
$query = $this->getQuery($productId, $recipients);

$response = $this->graphQlMutation($query);
self::assertEquals('Name', $response['sendEmailToFriend']['sender']['name']);
self::assertEquals('[email protected]', $response['sendEmailToFriend']['sender']['email']);
self::assertEquals('Lorem Ipsum', $response['sendEmailToFriend']['sender']['message']);
self::assertEquals('Recipient Name 1', $response['sendEmailToFriend']['recipients'][0]['name']);
self::assertEquals('[email protected]', $response['sendEmailToFriend']['recipients'][0]['email']);
self::assertEquals('Recipient Name 2', $response['sendEmailToFriend']['recipients'][1]['name']);
self::assertEquals('[email protected]', $response['sendEmailToFriend']['recipients'][1]['email']);
$response = $this->graphQlMutation($query, [], '', $this->getHeaderMap());
$this->assertResponse($response);
}

/**
Expand Down Expand Up @@ -311,6 +362,37 @@ public function sendFriendsErrorsDataProvider()
];
}

/**
* Generic assertions for send a friend response
*
* @param array $response
*/
private function assertResponse(array $response): void
{
self::assertEquals('Name', $response['sendEmailToFriend']['sender']['name']);
self::assertEquals('[email protected]', $response['sendEmailToFriend']['sender']['email']);
self::assertEquals('Lorem Ipsum', $response['sendEmailToFriend']['sender']['message']);
self::assertEquals('Recipient Name 1', $response['sendEmailToFriend']['recipients'][0]['name']);
self::assertEquals('[email protected]', $response['sendEmailToFriend']['recipients'][0]['email']);
self::assertEquals('Recipient Name 2', $response['sendEmailToFriend']['recipients'][1]['name']);
self::assertEquals('[email protected]', $response['sendEmailToFriend']['recipients'][1]['email']);
}

/**
* Retrieve customer authorization headers
*
* @param string $username
* @param string $password
* @return array
* @throws AuthenticationException
*/
private function getHeaderMap(string $username = '[email protected]', string $password = 'password'): array
{
$customerToken = $this->customerTokenService->createCustomerAccessToken($username, $password);
$headerMap = ['Authorization' => 'Bearer ' . $customerToken];
return $headerMap;
}

/**
* @param int $productId
* @param string $recipients
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
// TODO: Should be removed in scope of https://github.com/magento/graphql-ce/issues/167
declare(strict_types=1);

use Magento\Framework\App\Config\Storage\Writer;
use Magento\Framework\App\Config\Storage\WriterInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Framework\App\Config\ScopeConfigInterface;

$objectManager = Bootstrap::getObjectManager();
/** @var Writer $configWriter */
$configWriter = $objectManager->get(WriterInterface::class);

$configWriter->save('sendfriend/email/allow_guest', '0');

$scopeConfig = $objectManager->get(ScopeConfigInterface::class);
$scopeConfig->clean();
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
// TODO: Should be removed in scope of https://github.com/magento/graphql-ce/issues/167
declare(strict_types=1);

use Magento\Framework\App\Config\Storage\Writer;
use Magento\Framework\App\Config\Storage\WriterInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Framework\App\Config\ScopeConfigInterface;

$objectManager = Bootstrap::getObjectManager();
/** @var Writer $configWriter */
$configWriter = $objectManager->get(WriterInterface::class);

$configWriter->save('sendfriend/email/allow_guest', '1');

$scopeConfig = $objectManager->get(ScopeConfigInterface::class);
$scopeConfig->clean();

0 comments on commit 63762d6

Please sign in to comment.