authorizeBrowser example

public function testExportReadPrivileges(): void
    {
        $data = $this->prepareImportExportActionControllerTestData();

        $this->repository->create(array_values($data)$this->context);

        foreach ($data as $entry) {
            $client = $this->getBrowser();
            TestUser::createNewTestUser(
                $client->getContainer()->get(Connection::class),
                []
            )->authorizeBrowser($client);
            $client->request(
                'POST',
                '/api/_action/import-export/prepare',
                ['profileId' => $entry['id'], 'expireDate' => date('Y-m-d H:i:s')],
                [],
                ['Content-Type' => 'multipart/formdata']
            );

            $response = $client->getResponse();
            static::assertSame(Response::HTTP_FORBIDDEN, $response->getStatusCode());
            $response = json_decode($response->getContent(), true, 512, \JSON_THROW_ON_ERROR);
            


        $apiBrowser = KernelLifecycleManager::createBrowser($kernel$enableReboot);

        $apiBrowser->followRedirects();
        $apiBrowser->setServerParameters([
            'CONTENT_TYPE' => 'application/json',
            'HTTP_ACCEPT' => ['application/vnd.api+json,application/json'],
        ]);

        if ($authorized) {
            $this->authorizeBrowser($apiBrowser$scopes$permissions);
        }

        return $this->kernelBrowser = $apiBrowser;
    }

    public function assertEntityExists(TestBrowser $browser, string ...$params): void
    {
        $url = '/api/' . implode('/', $params);

        $browser->request('GET', $url);

        
static::assertSame(Response::HTTP_NO_CONTENT, $response->getStatusCode());

        $assigned = $this->getContainer()->get('integration.repository')
            ->search(new Criteria([$ids->get('integration')])$context);

        static::assertEquals(1, $assigned->count());
        static::assertTrue($assigned->first()->getAdmin());
    }

    public function testPreventCreateIntegrationWithoutPermissions(): void
    {
        $this->authorizeBrowser($this->getBrowser()[UserVerifiedScope::IDENTIFIER][]);
        $client = $this->getBrowser();

        $data = [
            'label' => 'integration',
            'accessKey' => AccessKeyHelper::generateAccessKey('integration'),
            'secretAccessKey' => AccessKeyHelper::generateSecretAccessKey(),
        ];

        $client->request('POST', '/api/integration', [][][], \json_encode($data, \JSON_THROW_ON_ERROR));

        $response = $client->getResponse();

        

        $cart = $this->generateDemoCart(2);
        $orderId = $this->persistCart($cart);

        /** @var OrderEntity $order */
        $order = $this->orderRepository->search(new Criteria([$orderId])$this->context)->get($orderId);
        static::assertNotNull($order);

        TestUser::createNewTestUser(
            $this->getContainer()->get(Connection::class),
            []
        )->authorizeBrowser($this->getBrowser());

        $endpoint = sprintf('/api/_action/order/%s/%s/document/invoice/preview', $orderId$order->getDeepLinkCode());

        $this->getBrowser()->request('GET', $endpoint);

        static::assertEquals(Response::HTTP_FORBIDDEN, $this->getBrowser()->getResponse()->getStatusCode());
        $response = json_decode((string) $this->getBrowser()->getResponse()->getContent(), true, 512, \JSON_THROW_ON_ERROR);
        static::assertNotEmpty($response['errors']);
        static::assertEquals($response['errors'][0]['code'], 'FRAMEWORK__MISSING_PRIVILEGE_ERROR');

        TestUser::createNewTestUser(
            

class AdminSearchControllerTest extends TestCase
{
    use AdminApiTestBehaviour;
    use AdminFunctionalTestBehaviour;
    use IntegrationTestBehaviour;

    protected function setup(): void
    {
        $roles = ['product:read', 'product_manufacturer:read', 'user:read'];

        $this->authorizeBrowser($this->getBrowser()[UserVerifiedScope::IDENTIFIER]$roles);

        $this->prepareTestData();
    }

    /** * @dataProvider searchDataProvider */
    public function testSearch(array $data, bool $hasResponse, array $expectedEntities, array $expectedErrors = []): void
    {
        $this->getBrowser()->request('POST', '/api/_admin/search', [][][]json_encode($data, \JSON_THROW_ON_ERROR) ?: null);
        $response = $this->getBrowser()->getResponse();
        
'order_delivery:create',
                'order_line_item:create',
                'order_transaction:create',
                'order_delivery_position:create',
                'mail_template_type:update',
                'customer:update',
            ];
            foreach ([true, false] as $testOrderOnly) {
                TestUser::createNewTestUser(
                    $browser->getContainer()->get(Connection::class),
                    $testOrderOnly ? $orderPrivileges : ['api_proxy_switch-customer', CreditOrderLineItemListener::ACL_ORDER_CREATE_DISCOUNT_PRIVILEGE],
                )->authorizeBrowser($browser);
                $browser->request('POST', $this->getCreateOrderApiUrl($salesChannelContext->getSalesChannel()->getId()));

                $response = $browser->getResponse()->getContent();
                $response = json_decode($response ?: '', true, 512, \JSON_THROW_ON_ERROR);

                static::assertArrayHasKey('errors', $responseprint_r($response, true));
                static::assertEquals('FRAMEWORK__MISSING_PRIVILEGE_ERROR', $response['errors'][0]['code'] ?? null);
                static::assertStringContainsString(
                    $testOrderOnly ? CreditOrderLineItemListener::ACL_ORDER_CREATE_DISCOUNT_PRIVILEGE : 'order_line_item:create',
                    $response['errors'][0]['detail'] ?? ''
                );
            }
public function testOneToManyInsertWithoutPermission(): void
    {
        $id = Uuid::randomHex();

        $data = ['id' => $id, 'name' => $id];
        $browser = $this->getBrowser();
        $connection = $this->getBrowser()->getContainer()->get(Connection::class);
        $user = TestUser::createNewTestUser($connection['country:create', 'country:read']);
        $admin = TestUser::getAdmin();

        $user->authorizeBrowser($browser);

        $browser->request('POST', '/api/country', [][][]json_encode($data, \JSON_THROW_ON_ERROR));
        $response = $browser->getResponse();
        static::assertSame(Response::HTTP_NO_CONTENT, $browser->getResponse()->getStatusCode()(string) $browser->getResponse()->getContent());
        static::assertNotEmpty($response->headers->get('Location'));
        static::assertEquals('http://localhost/api/country/' . $id$response->headers->get('Location'));

        $this->assertEntityExists($browser, 'country', $id);

        $data = [
            'id' => $id,
            
$response = $this->getBrowser()->getResponse();
        $privileges = json_decode($response->getContent(), true, 512, \JSON_THROW_ON_ERROR);

        static::assertNotContains('unit:read', $privileges);
        static::assertContains('system:clear:cache', $privileges);
        static::assertContains('my_custom_privilege', $privileges);
    }

    public function testGetAdditionalPrivilegesNoPermission(): void
    {
        try {
            $this->authorizeBrowser($this->getBrowser()[][]);
            $this->getBrowser()->request('GET', '/api/_action/acl/additional_privileges');
            $response = $this->getBrowser()->getResponse();

            static::assertEquals(Response::HTTP_FORBIDDEN, $response->getStatusCode()$response->getContent());
            static::assertEquals(MissingPrivilegeException::MISSING_PRIVILEGE_ERROR, json_decode($response->getContent(), true, 512, \JSON_THROW_ON_ERROR)['errors'][0]['code']$response->getContent());
        } finally {
            $this->resetBrowser();
        }
    }
}
int $resultQuantity
    ): void {
        $data = [
            'status' => 'success',
            'message' => 'This is a successful message',
            'adminOnly' => $adminOnly,
            'requiredPrivileges' => $requiredPrivileges,
        ];
        $this->notificationRepository->create([$data]$this->context);

        if (\is_array($userPrivileges)) {
            $this->authorizeBrowser($this->getBrowser()[]$userPrivileges);
        }

        $this->getBrowser()->request('GET', '/api/notification/message');

        static::assertEquals(200, $this->getBrowser()->getResponse()->getStatusCode());
        static::assertNotFalse($this->getBrowser()->getResponse()->getContent());

        $content = \json_decode($this->getBrowser()->getResponse()->getContent(), true, 512, \JSON_THROW_ON_ERROR);

        if ($resultQuantity === 0) {
            static::assertCount(0, $content['notifications']);

            
$this->kernelBrowser = null;
        $client = $this->getBrowser(true, [UserVerifiedScope::IDENTIFIER]);
        $client->request('DELETE', '/api/user/' . $id);

        $response = $client->getResponse();
        $content = json_decode((string) $response->getContent(), true);
        static::assertSame(Response::HTTP_NO_CONTENT, $response->getStatusCode()print_r($content, true));
    }

    public function testSetOwnProfileWithPermission(): void
    {
        $this->authorizeBrowser($this->getBrowser()[UserVerifiedScope::IDENTIFIER]['user_change_me']);
        $this->getBrowser()->request('PATCH', '/api/_info/me', ['firstName' => 'newName']);
        $responsePatch = $this->getBrowser()->getResponse();

        static::assertEquals(Response::HTTP_NO_CONTENT, $responsePatch->getStatusCode()(string) $responsePatch->getContent());

        $this->getBrowser()->request('GET', '/api/_info/me');
        $response = $this->getBrowser()->getResponse();

        static::assertEquals(Response::HTTP_OK, $response->getStatusCode()(string) $response->getContent());
        static::assertEquals('newName', json_decode((string) $response->getContent(), true)['data']['attributes']['firstName']);
    }

    
static::assertEquals('Forbidden', $response['errors'][0]['title']);
        static::assertStringContainsString('api-insufficient-permissions', $response['errors'][0]['detail']);
        static::assertStringContainsString('Missing privilege', $response['errors'][0]['detail']);
    }

    public function testMissingAclPrivilegesToAccessRoute(): void
    {
        $this->loadAppsFromDir(__DIR__ . '/_fixtures');

        $browser = $this->getBrowser();
        // no admin permissions         $this->authorizeBrowser($browser[][]);
        $browser->request('POST', '/api/script/simple-script');
        static::assertNotFalse($browser->getResponse()->getContent());

        $response = \json_decode($browser->getResponse()->getContent(), true, 512, \JSON_THROW_ON_ERROR);
        static::assertSame(Response::HTTP_FORBIDDEN, $browser->getResponse()->getStatusCode()print_r($response, true));

        static::assertArrayHasKey('errors', $response);
        static::assertCount(1, $response['errors']);
        static::assertEquals('Forbidden', $response['errors'][0]['title']);
        static::assertEquals('The user does not have the permission to do this action.', $response['errors'][0]['detail']);
    }

    
/** * @internal * * @group slow */
class UserConfigControllerTest extends TestCase
{
    use AdminFunctionalTestBehaviour;

    protected function setup(): void
    {
        $this->authorizeBrowser($this->getBrowser()[UserVerifiedScope::IDENTIFIER][]);
    }

    protected function tearDown(): void
    {
        $this->resetBrowser();
    }

    public function testGetConfigMe(): void
    {
        $configKey = 'me.read';

        
$hasCategoryIndexerMessage = $hasCategoryIndexerMessage ?: $message['message']->getIndexer() === 'category.indexer';
            }
        }

        static::assertTrue($hasSalesChannelIndexerMessage);
        static::assertFalse($hasCategoryIndexerMessage);
    }

    public function testCacheIndexEndpointNoPermissions(): void
    {
        try {
            $this->authorizeBrowser($this->getBrowser()[]['something']);
            $this->getBrowser()->request('POST', '/api/_action/index');

            /** @var JsonResponse $response */
            $response = $this->getBrowser()->getResponse();

            static::assertEquals(Response::HTTP_FORBIDDEN, $response->getStatusCode()(string) $response->getContent());
            $decode = json_decode((string) $response->getContent(), true, 512, \JSON_THROW_ON_ERROR);
            static::assertEquals(MissingPrivilegeException::MISSING_PRIVILEGE_ERROR, $decode['errors'][0]['code'](string) $response->getContent());
        } finally {
            $this->resetBrowser();
        }
    }
$file->method('getMimeType')->willReturn('foo');
        $file->method('getPathname')->willReturn(tempnam(sys_get_temp_dir(), __METHOD__));
        $request->files->set('file', $file);

        static::expectException(PluginNotAZipFileException::class);
        $controller->uploadExtensions($request, Context::createDefaultContext());
    }

    public function testUploadExtensionsWithInvalidPermissions(): void
    {
        $browser = $this->getBrowser();
        $this->authorizeBrowser($browser[]['system.plugin_maintain']);

        $browser->request('POST', '/api/_action/extension/upload');
        $response = $browser->getResponse();

        static::assertEquals(403, $response->getStatusCode());
        $body = \json_decode($response->getContent(), true, 512, \JSON_THROW_ON_ERROR);
        static::assertEquals('FRAMEWORK__MISSING_PRIVILEGE_ERROR', $body['errors'][0]['code']);
    }

    public function testUploadExtensionsWithValidPermissions(): void
    {
        
Home | Imprint | This part of the site doesn't use cookies.