Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Cart] Recalculate customer cart when log in #478

Merged
merged 5 commits into from
Jul 24, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 28 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,18 +79,39 @@ The latest documentation is available [here](https://app.swaggerhub.com/apis/Syl
# ...

sylius.security.shop_regex: "^/(?!admin|api/.*|api$|shop-api|media/.*)[^/]++" # shop-api has been added inside the brackets
shop_api.security.regex: "^/shop-api"
sylius_shop_api.security.regex: "^/shop-api"

# ...

security:
firewalls:
// ...

sylius_shop_api_login:
pattern: "%sylius_shop_api.security.regex%/login"
stateless: true
anonymous: true
form_login:
provider: sylius_shop_user_provider
login_path: /shop-api/login_check
check_path: /shop-api/login_check
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
require_previous_session: false

shop_api:
pattern: "%shop_api.security.regex%"
stateless: true
anonymous: true
sylius_shop_api:
pattern: "%sylius_shop_api.security.regex%"
stateless: true
anonymous: true
guard:
provider: sylius_shop_user_provider
authenticators:
- lexik_jwt_authentication.jwt_token_authenticator

access_control:
- { path: "%sylius_shop_api.security.regex%/login", role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: "%sylius_shop_api.security.regex%/register", role: IS_AUTHENTICATED_ANONYMOUSLY }

```

6. (optional) if you have installed `nelmio/NelmioCorsBundle` for Support of Cross-Origin Ajax Request,
Expand Down Expand Up @@ -142,16 +163,8 @@ sylius_shop_api:
- "MUG_MATERIAL_CODE"
```

### Authorization

By default no authorization is provided together with this bundle. But it is tested to work along with [LexikJWTAuthenticationBundle](https://github.com/lexik/LexikJWTAuthenticationBundle)
In order to check example configuration check
- [security.yml](https://github.com/Sylius/SyliusShopApiPlugin/blob/master/tests/Application/app/config/security.yml)
- [jwt parameters](https://github.com/Sylius/SyliusShopApiPlugin/blob/master/tests/Application/app/config/config.yml#L4-L7) and [jwt config](https://github.com/Sylius/SyliusShopApiPlugin/blob/master/tests/Application/app/config/config.yml#L55-L59) in config.yml
- [example rsa keys](https://github.com/Sylius/SyliusShopApiPlugin/tree/master/tests/Application/app/config/jwt)
- [login request](https://github.com/Sylius/SyliusShopApiPlugin/blob/master/tests/Controller/CustomerShopApiTest.php#L52-L68)

From the test app.
This plugin comes with an integration with [LexikJWTAuthenticationBundle](https://github.com/lexik/LexikJWTAuthenticationBundle/).
More information about security customizations may be found there.

## Testing

Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@
"php": "^7.2",

"sylius/sylius": "^1.4",
"lexik/jwt-authentication-bundle": "^2.5",
"symfony/messenger": "~4.3.0"
},
"require-dev": {
"lchrusciel/api-test-case": "^4.0",
"lexik/jwt-authentication-bundle": "^2.5",
"matthiasnoback/symfony-config-test": "^4.0",
"matthiasnoback/symfony-dependency-injection-test": "^4.0",
"phpspec/phpspec": "^5.0",
Expand Down
28 changes: 28 additions & 0 deletions doc/swagger.yml
Original file line number Diff line number Diff line change
Expand Up @@ -764,6 +764,25 @@ paths:
description: "There were validation errors"
500:
description: "Channel not found"

/login_check:
post:
tags:
- "users"
summary: "Log user in"
description: "This action allows to log existing user in"
operationId: "loginUser"
parameters:
- name: "content"
in: "body"
required: true
schema:
$ref: "#/definitions/LoginRequest"
responses:
204:
description: "The user was successfully created"
400:
description: "There were validation errors"
/orders:
parameters:
- $ref: "#/parameters/ChannelCode"
Expand Down Expand Up @@ -1569,6 +1588,15 @@ definitions:
channel:
type: "string"
example: "WEB_GB"
LoginRequest:
type: "object"
properties:
_username:
type: "string"
example: "test@example.com"
_password:
type: "string"
example: "test12334verysecure"
UpdateUserRequest:
type: "object"
properties:
Expand Down
91 changes: 91 additions & 0 deletions src/EventListener/CartBlamerListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
<?php

/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace Sylius\ShopApiPlugin\EventListener;

use Doctrine\Common\Persistence\ObjectManager;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTCreatedEvent;
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Core\Model\ShopUserInterface;
use Sylius\Component\Core\Repository\OrderRepositoryInterface;
use Sylius\Component\Order\Context\CartContextInterface;
use Sylius\Component\Order\Context\CartNotFoundException;
use Symfony\Component\HttpFoundation\RequestStack;
use Webmozart\Assert\Assert;

final class CartBlamerListener
{
/** @var ObjectManager */
private $cartManager;

/** @var CartContextInterface */
private $cartContext;

/** @var OrderRepositoryInterface */
private $cartRepository;
/** @var RequestStack */
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

missing space

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing blank line

private $requestStack;

public function __construct(
ObjectManager $cartManager,
CartContextInterface $cartContext,
OrderRepositoryInterface $cartRepository,
RequestStack $requestStack
) {
$this->cartManager = $cartManager;
$this->cartContext = $cartContext;
$this->cartRepository = $cartRepository;
$this->requestStack = $requestStack;
}

public function onJwtLogin(JWTCreatedEvent $interactiveLoginEvent): void
{
$user = $interactiveLoginEvent->getUser();
$request = $this->requestStack->getCurrentRequest();

Assert::notNull($request);

if (!$user instanceof ShopUserInterface) {
return;
}

$cart = $this->getCart($request->request->get('token'));

if (null === $cart) {
return;
}

$cart->setCustomer($user->getCustomer());
$this->cartManager->persist($cart);
$this->cartManager->flush();
}

private function getCart(?string $token): ?OrderInterface
{
if (null !== $token) {
/** @var OrderInterface $cart */
$cart = $this->cartRepository->findOneBy(['tokenValue' => $token]);

return $cart;
}

try {
/** @var OrderInterface $cart */
$cart = $this->cartContext->getCart();

return $cart;
} catch (CartNotFoundException $exception) {
return null;
}
}
}
49 changes: 49 additions & 0 deletions src/EventListener/UserCartRecalculationListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

declare(strict_types=1);

namespace Sylius\ShopApiPlugin\EventListener;

use Doctrine\Common\Persistence\ObjectManager;
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Order\Context\CartContextInterface;
use Sylius\Component\Order\Context\CartNotFoundException;
use Sylius\Component\Order\Processor\OrderProcessorInterface;
use Webmozart\Assert\Assert;

final class UserCartRecalculationListener
{
/** @var CartContextInterface */
private $cartContext;

/** @var OrderProcessorInterface */
private $orderProcessor;

/** @var ObjectManager */
private $cartManager;

public function __construct(
CartContextInterface $cartContext,
OrderProcessorInterface $orderProcessor,
ObjectManager $cartManager
) {
$this->cartContext = $cartContext;
$this->orderProcessor = $orderProcessor;
$this->cartManager = $cartManager;
}

public function recalculateCartWhileLogin(): void
{
try {
$cart = $this->cartContext->getCart();
} catch (CartNotFoundException $exception) {
return;
}

Assert::isInstanceOf($cart, OrderInterface::class);

$this->orderProcessor->process($cart);

$this->cartManager->flush();
}
}
4 changes: 4 additions & 0 deletions src/Resources/config/routing.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,7 @@ sylius_shop_api_address_book:
sylius_shop_api_order:
resource: "@ShopApiPlugin/Resources/config/routing/order.yml"
prefix: /shop-api

sylius_shop_api_login_check:
methods: [POST]
path: /shop-api/login_check
18 changes: 18 additions & 0 deletions src/Resources/config/services.xml
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,24 @@
<argument type="service" id="sylius.context.channel" />
</service>

<service
id="sylius.listener.cart_blamer"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wrong indentation

class="Sylius\ShopApiPlugin\EventListener\CartBlamerListener"
>
<argument type="service" id="sylius.manager.order" />
<argument type="service" id="sylius.context.cart" />
<argument type="service" id="sylius.repository.order" />
<argument type="service" id="request_stack" />
<tag name="kernel.event_listener" event="lexik_jwt_authentication.on_jwt_created" method="onJwtLogin" />
</service>

<service id="sylius.listener.user_cart_recalculation" class="Sylius\ShopApiPlugin\EventListener\UserCartRecalculationListener">
<argument type="service" id="sylius.context.cart" />
<argument type="service" id="sylius.order_processing.order_processor" />
<argument type="service" id="sylius.manager.order" />
<tag name="kernel.event_listener" event="lexik_jwt_authentication.on_jwt_created" method="recalculateCartWhileLogin" />
</service>

<!-- Removing the create cart context from composite context (see: https://github.com/Sylius/Sylius/issues/10192) -->
<service id="sylius.context.cart.new" class="Sylius\Component\Order\Context\CartContext">
<argument type="service" id="sylius.factory.order" />
Expand Down
12 changes: 6 additions & 6 deletions tests/Application/config/packages/security.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ parameters:
sylius.security.admin_regex: "^/admin"
sylius.security.api_regex: "^/api"
sylius.security.shop_regex: "^/(?!admin|api/.*|api$|media/.*)[^/]++"
shop_api.security.regex: "^/shop-api"
sylius_shop_api.security.regex: "^/shop-api"

security:
providers:
Expand Down Expand Up @@ -52,7 +52,7 @@ security:
anonymous: true

sylius_shop_api_login:
pattern: "%shop_api.security.regex%/login"
pattern: "%sylius_shop_api.security.regex%/login"
stateless: true
anonymous: true
form_login:
Expand All @@ -63,8 +63,8 @@ security:
failure_handler: lexik_jwt_authentication.handler.authentication_failure
require_previous_session: false

shop_api:
pattern: "%shop_api.security.regex%"
sylius_shop_api:
pattern: "%sylius_shop_api.security.regex%"
stateless: true
anonymous: true
guard:
Expand Down Expand Up @@ -115,11 +115,11 @@ security:
- { path: "%sylius.security.admin_regex%/login", role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: "%sylius.security.api_regex%/login", role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: "%sylius.security.shop_regex%/login", role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: "%shop_api.security.regex%/login", role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: "%sylius_shop_api.security.regex%/login", role: IS_AUTHENTICATED_ANONYMOUSLY }

- { path: "%sylius.security.shop_regex%/register", role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: "%sylius.security.shop_regex%/verify", role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: "%shop_api.security.regex%/register", role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: "%sylius_shop_api.security.regex%/register", role: IS_AUTHENTICATED_ANONYMOUSLY }

- { path: "%sylius.security.admin_regex%", role: ROLE_ADMINISTRATION_ACCESS }
- { path: "%sylius.security.api_regex%/.*", role: ROLE_API_ACCESS }
Expand Down
4 changes: 0 additions & 4 deletions tests/Application/config/routes.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,3 @@ sylius:

sylius_shop_api:
resource: "@ShopApiPlugin/Resources/config/routing.yml"

sylius_shop_api_login_check:
methods: [POST]
path: /shop-api/login_check
31 changes: 31 additions & 0 deletions tests/Controller/Cart/CartPickupApiTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@

namespace Tests\Sylius\ShopApiPlugin\Controller\Cart;

use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Core\Repository\OrderRepositoryInterface;
use Sylius\ShopApiPlugin\Command\Cart\PickupCart;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;
use Tests\Sylius\ShopApiPlugin\Controller\JsonApiTestCase;
use Tests\Sylius\ShopApiPlugin\Controller\Utils\ShopUserLoginTrait;

Expand Down Expand Up @@ -51,4 +54,32 @@ public function it_only_creates_one_cart_if_user_is_logged_in(): void

$this->assertCount(1, $orders, 'Only one cart should be created');
}

/**
* @test
*/
public function it_does_not_create_a_new_cart_if_cart_was_picked_up_before_logging_in(): void
{
$this->loadFixturesFromFiles(['shop.yml', 'customer.yml']);

$token = 'SDAOSLEFNWU35H3QLI5325';

/** @var MessageBusInterface $bus */
$bus = $this->get('sylius_shop_api_plugin.command_bus');
$bus->dispatch(new PickupCart($token, 'WEB_GB'));

$this->logInUserWithCart('oliver@queen.com', '123password', $token);

/** @var OrderRepositoryInterface $orderRepository */
$orderRepository = $this->get('sylius.repository.order');
$orders = $orderRepository->findAll();

$this->assertCount(1, $orders, 'Only one cart should be created');

/** @var OrderInterface $order */
$order = $orders[0];
$customer = $order->getCustomer();
$this->assertNotNull($customer, 'Cart should have customer assigned, but it has not.');
$this->assertSame('oliver@queen.com', $customer->getEmail());
}
}
Loading