Search code examples
shopwareshopware6

Limiting Access to Documents with Context in Shopware 6


We've built a custom endpoint to retrieve documents that are part of an order. In that process we do a search for documents based on the orderId, using the document.repository injected into the service.

However, we've noticed that as long as you know the ID of the document any user can retrieve it, regardless of the sw-context-token they provide. Are we incorrectly assuming when we pass the Context into the repository search that it handles if the user is allowed to access the resources returned or not?

The reason we're getting documents this way is to be able to get documents on an order with their sent status set to 0, which if you request an order entity with documents loaded they wont be returned unless they've been sent.


Solution

  • Are we incorrectly assuming when we pass the Context into the repository search that it handles if the user is allowed to access the resources returned or not?

    Yes.

    You will have to secure the endpoint yourself. You could set the endpoint to require the user to be logged in and fetch the document with a filter on the associations up to the customer.

    #[Route(path: '/custom/endpoint/{documentId}', name: 'custom.endpoint.document', methods: ['GET'], defaults: ['_loginRequired' => true, '_loginRequiredAllowGuest' => true])]
    public function download(string $documentId, SalesChannelContext $context): Response
    {
        if ($context->getCustomer() === null) {
            throw CartException::customerNotLoggedIn();
        }
    
        $criteria = new Criteria([$documentId]);
        $criteria->addFilter(new EqualsFilter('order.orderCustomer.customerId', $context->getCustomer()->getId()));
    
        /** @var null|DocumentEntity $document */
        $document = $this->documentRepository->search($criteria, $context->getContext())->first();
        
        if (!$document) {
            throw new \InvalidArgumentException();
        }
    
        $document = $this->documentGenerator->readDocument($document->getId(), $context->getContext(), $document->getDeepLinkCode());
    
        // ...
    }