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

More precise error messages #301

Merged
merged 9 commits into from
Aug 31, 2018
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
20 changes: 15 additions & 5 deletions doc/swagger.yml
Original file line number Diff line number Diff line change
Expand Up @@ -912,14 +912,18 @@ paths:
schema:
$ref: "#/definitions/LoggedInCustomerAddressBookAddress"
responses:
204:
201:
description: "Successfully created the address"
schema:
- $ref: "#/definitions/LoggedInCustomerAddressBookAddress"
400:
description: "Validation failed"
schema:
$ref: "#/definitions/GeneralError"
401:
description: "No user is logged in"
500:
Copy link
Member

Choose a reason for hiding this comment

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

It should be 404, I guess

Copy link
Member Author

Choose a reason for hiding this comment

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

As you may have noticed I have added authorization symbols to the documentation. And the address book is something that only logged in users can see. If you are not logged in and try to call a route where you need to be logged in I wanted to return a 401 Unauthorized.

Copy link
Member

Choose a reason for hiding this comment

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

I suppose it is not the scope of this PR anyway?

Copy link
Member Author

Choose a reason for hiding this comment

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

The change in the documentation? That is already implemented. But the only parts that are behind a login wall are the address book and some of the customer endpoints.

Copy link
Member

Choose a reason for hiding this comment

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

Sorry, I was just confused, that we are handling error with 500 code. But this is totally not part of this PR. I'm just missing some part why, but this is rather general question about current codebase :)

Copy link
Member Author

Choose a reason for hiding this comment

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

True, the problem with the API was that assertions throw exceptions which are not very helpful to a user.

description: "No logged in user or the user does not own the address"
description: "The user does not own the address"
security:
- bearerAuth: []
/address-book/{id}:
Expand Down Expand Up @@ -950,8 +954,10 @@ paths:
description: "Validation failed"
schema:
$ref: "#/definitions/GeneralError"
401:
description: "No user is logged in"
500:
description: "No logged in user or the user does not own the address"
description: "The user does not own the address"
security:
- bearerAuth: []
delete:
Expand All @@ -973,8 +979,10 @@ paths:
description: "Validation failed"
schema:
$ref: "#/definitions/GeneralError"
401:
description: "No user is logged in"
500:
description: "No logged in user or the user does not own the address"
description: "The user does not own the address"
security:
- bearerAuth: []
/address-book/{id}/default:
Expand All @@ -997,8 +1005,10 @@ paths:
description: "Validation failed"
schema:
$ref: "#/definitions/GeneralError"
401:
description: "No user is logged in"
500:
description: "No logged in user or the user does not own the address"
description: "The user does not own the address"
security:
- bearerAuth: []
securityDefinitions:
Expand Down
46 changes: 46 additions & 0 deletions spec/Provider/LoggedInUserProviderSpec.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);

namespace spec\Sylius\ShopApiPlugin\Provider;

use PhpSpec\ObjectBehavior;
use Sylius\Component\Core\Model\ShopUserInterface;
use Sylius\ShopApiPlugin\Provider\LoggedInUserProviderInterface;
use Symfony\Component\Security\Core\Exception\TokenNotFoundException;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;

final class LoggedInUserProviderSpec extends ObjectBehavior
{
function let(TokenStorageInterface $tokenStorage)
{
$this->beConstructedWith($tokenStorage);
}

function it_is_reviewer_subject_provider()
{
$this->shouldImplement(LoggedInUserProviderInterface::class);
}

function it_throws_an_error_if_there_is_no_user_logged_in(
TokenStorageInterface $tokenStorage,
TokenInterface $token
) {
$token->getUser()->shouldBeCalled()->willReturn(null);
$tokenStorage->getToken()->shouldBeCalled()->willReturn($token);

$this->shouldThrow(TokenNotFoundException::class)->during('provide');
}

function it_returns_the_logged_in_user_if_there_is_one(
TokenStorageInterface $tokenStorage,
TokenInterface $token,
ShopUserInterface $shopUser
)
Copy link
Member

Choose a reason for hiding this comment

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

CS

{
$token->getUser()->shouldBeCalled()->willReturn($shopUser);
$tokenStorage->getToken()->shouldBeCalled()->willReturn($token);

$this->provide()->shouldReturn($shopUser);
}
}
8 changes: 4 additions & 4 deletions spec/Validator/AddressExistsValidatorSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
use Sylius\Component\Core\Model\CustomerInterface;
use Sylius\Component\Core\Model\ShopUserInterface;
use Sylius\Component\Core\Repository\AddressRepositoryInterface;
use Sylius\ShopApiPlugin\Provider\CurrentUserProviderInterface;
use Sylius\ShopApiPlugin\Provider\LoggedInUserProviderInterface;
use Sylius\ShopApiPlugin\Validator\Constraints\AddressExists;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

Expand All @@ -19,7 +19,7 @@ final class AddressExistsValidatorSpec extends ObjectBehavior
function let(
ExecutionContextInterface $executionContext,
AddressRepositoryInterface $addressRepository,
CurrentUserProviderInterface $currentUserProvider
LoggedInUserProviderInterface $currentUserProvider
) {
$this->beConstructedWith($addressRepository, $currentUserProvider);

Expand All @@ -30,7 +30,7 @@ function it_does_not_add_constraint_if_address_exists_and_its_owned_by_current_u
AddressInterface $address,
ShopUserInterface $shopUser,
CustomerInterface $customerOwner,
CurrentUserProviderInterface $currentUserProvider,
LoggedInUserProviderInterface $currentUserProvider,
AddressRepositoryInterface $addressRepository,
ExecutionContextInterface $executionContext
) {
Expand Down Expand Up @@ -61,7 +61,7 @@ function it_adds_constraint_if_address_does_not_exits_exists(
function it_adds_constraint_if_current_user_is_not_address_owner(
AddressInterface $address,
AddressRepositoryInterface $addressRepository,
CurrentUserProviderInterface $currentUserProvider,
LoggedInUserProviderInterface $currentUserProvider,
ShopUserInterface $shopUser,
CustomerInterface $customerOwner,
ExecutionContextInterface $executionContext
Expand Down
73 changes: 57 additions & 16 deletions src/Controller/AddressBook/CreateAddressAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,18 @@
use FOS\RestBundle\View\View;
use FOS\RestBundle\View\ViewHandlerInterface;
use League\Tactician\CommandBus;
use Sylius\Component\Core\Model\Customer;
use Sylius\Component\Core\Model\ShopUserInterface;
use Sylius\Component\Core\Repository\AddressRepositoryInterface;
use Sylius\ShopApiPlugin\Command\CreateAddress;
use Sylius\ShopApiPlugin\Factory\AddressBookViewFactoryInterface;
use Sylius\ShopApiPlugin\Factory\ValidationErrorViewFactoryInterface;
use Sylius\ShopApiPlugin\Model\Address;
use Sylius\ShopApiPlugin\Provider\CurrentUserProviderInterface;
use Sylius\ShopApiPlugin\Provider\LoggedInUserProviderInterface;
use Sylius\ShopApiPlugin\View\AddressBookView;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\Exception\TokenNotFoundException;
use Symfony\Component\Validator\Validator\ValidatorInterface;

final class CreateAddressAction
Expand All @@ -39,36 +44,45 @@ final class CreateAddressAction
private $validationErrorViewFactory;

/**
* @var TokenStorage
* @var LoggedInUserProviderInterface
*/
private $tokenStorage;
private $loggedInUserProvider;

/**
* @var AddressBookViewFactoryInterface
*/
private $addressViewFactory;

/**
* @var CurrentUserProviderInterface
* @var AddressRepositoryInterface
*/
private $currentUserProvider;
private $addressRepository;

/**
* @param ViewHandlerInterface $viewHandler
* @param CommandBus $bus
* @param ValidatorInterface $validator
* @param ValidationErrorViewFactoryInterface $validationErrorViewFactory
* @param TokenStorage $tokenStorage
* @param CurrentUserProviderInterface $currentUserProvider
* @param AddressBookViewFactoryInterface $addressViewFactory
* @param AddressRepositoryInterface $addressRepository
* @param LoggedInUserProviderInterface $loggedInUserProvider
*/
public function __construct(
ViewHandlerInterface $viewHandler,
CommandBus $bus,
ValidatorInterface $validator,
ValidationErrorViewFactoryInterface $validationErrorViewFactory,
TokenStorage $tokenStorage,
CurrentUserProviderInterface $currentUserProvider
AddressBookViewFactoryInterface $addressViewFactory,
AddressRepositoryInterface $addressRepository,
LoggedInUserProviderInterface $loggedInUserProvider
) {
$this->viewHandler = $viewHandler;
$this->bus = $bus;
$this->validator = $validator;
$this->validationErrorViewFactory = $validationErrorViewFactory;
$this->tokenStorage = $tokenStorage;
$this->currentUserProvider = $currentUserProvider;
$this->addressViewFactory = $addressViewFactory;
$this->addressRepository = $addressRepository;
$this->loggedInUserProvider = $loggedInUserProvider;
}

/**
Expand All @@ -83,13 +97,40 @@ public function __invoke(Request $request): Response
$validationResults = $this->validator->validate($addressModel);

if (0 !== count($validationResults)) {
return $this->viewHandler->handle(View::create($this->validationErrorViewFactory->create($validationResults), Response::HTTP_BAD_REQUEST));
return $this->viewHandler->handle(
View::create($this->validationErrorViewFactory->create($validationResults), Response::HTTP_BAD_REQUEST)
);
}

$user = $this->currentUserProvider->provide();
try {
/** @var ShopUserInterface $user */
$user = $this->loggedInUserProvider->provide();
} catch (TokenNotFoundException $exception) {
return $this->viewHandler->handle(View::create(null, Response::HTTP_UNAUTHORIZED));
}

if (($customer = $user->getCustomer()) !== null) {
Copy link
Member

Choose a reason for hiding this comment

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

Not needed doubled brackets

$this->bus->handle(new CreateAddress($addressModel, $user->getEmail()));

$view = View::create($this->getLastInsertedAddress($customer), Response::HTTP_CREATED);
} else {
$view = View::create(['message' => 'The user is not a customer'], Response::HTTP_BAD_REQUEST);
}

$this->bus->handle(new CreateAddress($addressModel, $user->getEmail()));
return $this->viewHandler->handle($view);
}

/**
* Returns the id that was inserted last in the address book
*
* @param Customer $customer
*
* @return AddressBookView
*/
private function getLastInsertedAddress(Customer $customer): AddressBookView
{
$addresses = $this->addressRepository->findByCustomer($customer);

return $this->viewHandler->handle(View::create(null, Response::HTTP_NO_CONTENT));
return $this->addressViewFactory->create(end($addresses), $customer);
}
}
51 changes: 29 additions & 22 deletions src/Controller/AddressBook/RemoveAddressAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,14 @@
use FOS\RestBundle\View\View;
use FOS\RestBundle\View\ViewHandlerInterface;
use League\Tactician\CommandBus;
use Sylius\Component\Core\Model\ShopUserInterface;
use Sylius\ShopApiPlugin\Command\RemoveAddress;
use Sylius\ShopApiPlugin\Factory\ValidationErrorViewFactory;
use Sylius\ShopApiPlugin\Provider\CurrentUserProviderInterface;
use Sylius\ShopApiPlugin\Provider\LoggedInUserProviderInterface;
use Sylius\ShopApiPlugin\Request\RemoveAddressRequest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Exception\TokenNotFoundException;
use Symfony\Component\Validator\Validator\ValidatorInterface;

final class RemoveAddressAction
Expand All @@ -39,56 +40,62 @@ final class RemoveAddressAction
private $bus;

/**
* @var TokenStorageInterface
* @var LoggedInUserProviderInterface
*/
private $tokenStorage;

/**
* @var CurrentUserProviderInterface
*/
private $currentUserProvider;
private $loggedInUserProvider;

/**
* @param ViewHandlerInterface $viewHandler
* @param ValidatorInterface $validator
* @param ValidationErrorViewFactory $validationErrorViewFactory
* @param CommandBus $bus
* @param TokenStorageInterface $tokenStorage
* @param CurrentUserProviderInterface $currentUserProvider
* @param LoggedInUserProviderInterface $loggedInUserProvider
*/
public function __construct(
ViewHandlerInterface $viewHandler,
ValidatorInterface $validator,
ValidationErrorViewFactory $validationErrorViewFactory,
CommandBus $bus,
TokenStorageInterface $tokenStorage,
CurrentUserProviderInterface $currentUserProvider
LoggedInUserProviderInterface $loggedInUserProvider
) {
$this->viewHandler = $viewHandler;
$this->validator = $validator;
$this->validationErrorViewFactory = $validationErrorViewFactory;
$this->bus = $bus;
$this->tokenStorage = $tokenStorage;
$this->currentUserProvider = $currentUserProvider;
$this->loggedInUserProvider = $loggedInUserProvider;
}

/**
* Removes an address from the address book
*
* @param Request $request
*/
public function __invoke(Request $request): Response
{
$removeAddressRequest = new RemoveAddressRequest($request);

$validationResults = $this->validator->validate($removeAddressRequest);

if (0 !== count($validationResults)) {
return $this->viewHandler->handle(View::create($this->validationErrorViewFactory->create($validationResults), Response::HTTP_BAD_REQUEST));
return $this->viewHandler->handle(
View::create($this->validationErrorViewFactory->create($validationResults), Response::HTTP_BAD_REQUEST)
);
}

$user = $this->currentUserProvider->provide();
try {
/** @var ShopUserInterface $user */
$user = $this->loggedInUserProvider->provide();
} catch (TokenNotFoundException $exception) {
return $this->viewHandler->handle(View::create(null, Response::HTTP_UNAUTHORIZED));
}

$this->bus->handle(new RemoveAddress(
$request->attributes->get('id'),
$user->getEmail()
));
if ($user->getCustomer() !== null) {
$this->bus->handle(new RemoveAddress($removeAddressRequest->id(), $user->getEmail()));
$view = View::create(null, Response::HTTP_NO_CONTENT);
} else {
$view = View::create(['message' => 'The user is not a customer'], Response::HTTP_BAD_REQUEST);
}

return $this->viewHandler->handle(View::create('', Response::HTTP_NO_CONTENT));
return $this->viewHandler->handle($view);
}
}
Loading