AdminApiSource example

use PHPUnit\Framework\TestCase;
use Shopware\Core\Framework\Api\Context\AdminApiSource;

/** * @internal */
class AdminApiSourceTest extends TestCase
{
    public function testPermissions(): void
    {
        $apiSource = new AdminApiSource(null, null);
        $apiSource->setPermissions([
            'product:list',
            'order:delete',
        ]);

        static::assertTrue($apiSource->isAllowed('product:list'));
        static::assertTrue($apiSource->isAllowed('order:delete'));

        static::assertFalse($apiSource->isAllowed('product:delete'));
        static::assertFalse($apiSource->isAllowed('order:list'));
    }
}
$result = $orderRepository->search(
            new Criteria([$payload['id']]),
            $context
        )->first();

        static::assertEquals($userId$result->getCreatedById());
    }

    private function getAdminContext($userId): Context
    {
        $source = new AdminApiSource($userId);
        $source->setPermissions([
            'order:list',
            'order:create',
            'order:update',
            'order_customer:create',
            'order_address:create',
        ]);

        return new Context($source);
    }

    
->with('core.store.shopSecret')
            ->willReturn('store-secret');

        $provider = new StoreRequestOptionsProvider(
            $this->configureUserRepositorySearchMock(new UserCollection()static::once()),
            $systemConfigService,
            new InstanceService('sw-version', 'instance-id'),
            static::createMock(LocaleProvider::class)
        );

        $authHeaders = $provider->getAuthenticationHeader(
            Context::createDefaultContext(new AdminApiSource('user-id'))
        );

        static::assertArrayHasKey('X-Shopware-Shop-Secret', $authHeaders);
        static::assertEquals('store-secret', $authHeaders['X-Shopware-Shop-Secret']);
    }

    public function testGetAuthenticationHeaderDoesNotContainsShopSecretIfNotExists(): void
    {
        $systemConfigService = static::createMock(SystemConfigService::class);
        $systemConfigService->expects(static::once())
            ->method('getString')
            

        $response = new Response(401, [], '{"code":"ShopwarePlatformException-1"}');

        $userRepository = $this->getContainer()->get('user.repository');
        /** @var UserEntity $adminUser */
        $adminUser = $userRepository->search(new Criteria(), Context::createDefaultContext())->first();
        $userRepository->update([[
            'id' => $adminUser->getId(),
            'store_token' => 's3cr3t',
        ]], Context::createDefaultContext());

        $context = new Context(new AdminApiSource($adminUser->getId()));

        $request = new Request(
            [],
            [],
            [
                'sw-context' => $context,
            ]
        );

        $requestStack = new RequestStack();
        $requestStack->push($request);

        

class FirstRunWizardClientTest extends TestCase
{
    private Context $context;

    protected function setUp(): void
    {
        $this->context = new Context(new AdminApiSource(Uuid::randomHex()));
    }

    public function testFrwLogin(): void
    {
        $firstRunWizardUserToken = [
            'firstRunWizardUserToken' => [
                'token' => 'frw-us3r-t0k3n',
                'expirationDate' => (new \DateTimeImmutable('2021-01-01 00:00:00'))->format(Defaults::STORAGE_DATE_TIME_FORMAT),
            ],
        ];

        
$hook->getContext()->getRounding()
        );
    }

    private function getAppContextSource(ScriptAppInformation $scriptAppInformation): AdminApiSource
    {
        if (\array_key_exists($scriptAppInformation->getAppId()$this->appSources)) {
            return $this->appSources[$scriptAppInformation->getAppId()];
        }

        $privileges = $this->fetchPrivileges($scriptAppInformation->getAppId());
        $source = new AdminApiSource(null, $scriptAppInformation->getIntegrationId());
        $source->setIsAdmin(false);
        $source->setPermissions($privileges);

        return $this->appSources[$scriptAppInformation->getAppId()] = $source;
    }

    private function fetchPrivileges(string $appId): array
    {
        $privileges = $this->connection->fetchOne(' SELECT `acl_role`.`privileges` AS `privileges` FROM `acl_role` INNER JOIN `app` ON `app`.`acl_role_id` = `acl_role`.`id` WHERE `app`.`id` = :appId ',
static::assertEquals('en-GB', $provider->getLocaleFromContext(Context::createDefaultContext()));
    }

    public function testGetLocaleFromContextReturnsEnGbIfNoUserIsAssociated(): void
    {
        $provider = new LocaleProvider(static::createMock(EntityRepository::class));

        static::assertEquals(
            'en-GB',
            $provider->getLocaleFromContext(Context::createDefaultContext(
                new AdminApiSource(null, 'i-am-an-integration')
            ))
        );
    }

    public function testGetLocaleFromContextReturnsLocaleFromUser(): void
    {
        $context = Context::createDefaultContext(new AdminApiSource('user-id', null));

        $userLocale = new LocaleEntity();
        $userLocale->setCode('user-locale');

        
/** * @internal */
class RouteScopeListenerTest extends TestCase
{
    use IntegrationTestBehaviour;

    public function testRouteScopeListenerFailsHardWithoutMasterRequest(): void
    {
        $listener = $this->getContainer()->get(RouteScopeListener::class);

        $request = $this->createRequest('/api', 'api', new AdminApiSource(null, null));

        $event = $this->createEvent($request);

        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage('Unable to check the request scope without master request');
        $listener->checkScope($event);
    }

    public function testRouteScopeListenerIgnoresSymfonyControllers(): void
    {
        $listener = $this->getContainer()->get(RouteScopeListener::class);

        
'password' => TestDefaults::HASHED_PASSWORD,
                'firstName' => 'Foo',
                'lastName' => 'Bar',
                'email' => 'foo@bar.com',
                'storeToken' => Uuid::randomHex(),
                'admin' => true,
                'aclRoles' => [],
            ],
        ];

        $this->getContainer()->get('user.repository')->create($data, Context::createDefaultContext());
        $source = new AdminApiSource($userId);
        $source->setIsAdmin(true);

        return Context::createDefaultContext($source);
    }

    private function setLicensesRequest(string $licenseBody): void
    {
        $this->getRequestHandler()->reset();
        $this->getRequestHandler()->append(new Response(200, []$licenseBody));
    }

    


        $criteria = new Criteria();
        $criteria->addFilter(new EqualsFilter('user.username', $user));

        $userId = $this->userRepository->searchIds($criteria$context)->firstId();

        if ($userId === null) {
            throw new \RuntimeException('User not found');
        }

        $userContext = new Context(new AdminApiSource($userId));

        if ($shopwareId === null || $password === null) {
            throw new StoreInvalidCredentialsException();
        }

        try {
            $this->storeClient->loginWithShopwareId($shopwareId$password$userContext);
        } catch (ClientException $exception) {
            throw new StoreApiException($exception);
        }

        
/** * @internal */
class ApiRouteScopeTest extends TestCase
{
    use IntegrationTestBehaviour;

    public static function provideAllowedData()
    {
        return [
            [new AdminApiSource(null, null), true],
            [new AdminApiSource(null, null), false],
            [new SystemSource(), false],
        ];
    }

    public static function provideForbiddenData()
    {
        return [
            [new SalesChannelApiSource(Uuid::randomHex()), true],
            [new SystemSource(), true],
        ];
    }

        $this->defaultContext = Context::createDefaultContext();
        $this->userRepository = $this->getContainer()->get('user.repository');
    }

    public function testCheckLoginWithoutStoreToken(): void
    {
        /** @var UserEntity $adminUser */
        $adminUser = $this->userRepository->search(new Criteria()$this->defaultContext)->first();

        $storeController = $this->getStoreController();
        $context = new Context(new AdminApiSource($adminUser->getId()));

        $response = $storeController->checkLogin($context)->getContent();
        static::assertIsString($response);

        $response = json_decode($response, true, 512, \JSON_THROW_ON_ERROR);
        static::assertNull($response['userInfo']);
    }

    public function testLoginWithCorrectCredentials(): void
    {
        $request = new Request([][
            
'username' => 'foobar',
                'password' => 'asdasdasdasd',
                'firstName' => 'Foo',
                'lastName' => 'Bar',
                'email' => Uuid::randomHex() . '@bar.com',
                'storeToken' => $storeToken,
            ],
        ];

        $this->getUserRepository()->create($data, Context::createDefaultContext());

        $source = new AdminApiSource($userId);
        $source->setIsAdmin(true);

        return Context::createDefaultContext($source);
    }

    protected function getStoreTokenFromContext(Context $context): string
    {
        /** @var AdminApiSource $source */
        $source = $context->getSource();

        $userId = $source->getUserId();

        
class ImportExportHandlerTest extends TestCase
{
    /** * @dataProvider dataProviderForTestImportExport */
    public function testImportExportHandlerDispatchesMessage(string $activity): void
    {
        $messageBus = new CollectingMessageBus();

        $factory = $this->createMock(ImportExportFactory::class);

        $adminSource = new AdminApiSource('userId');
        $adminSource->setIsAdmin(true);
        $context = Context::createDefaultContext($adminSource);

        $importExportHandler = new ImportExportHandler($messageBus$factory);

        $logEntity = new ImportExportLogEntity();
        $logEntity->setActivity($activity);
        $logEntity->setState(Progress::STATE_PROGRESS);
        $logEntity->setId('logId');

        $progress = new Progress($logEntity->getId()$logEntity->getState());

        
$this->validator = new AclAnnotationValidator($this->connection);
    }

    /** * @dataProvider annotationProvider * * @param list<string> $privileges * @param list<string> $acl */
    public function testValidateRequestAsRouteAttribute(array $privileges, array $acl, bool $pass): void
    {
        $source = new AdminApiSource(null, null);
        $source->setPermissions($privileges);

        $context = new Context(
            $source,
            [],
            Defaults::CURRENCY,
            [Defaults::LANGUAGE_SYSTEM]
        );

        $request = new Request();
        $request->attributes->set(PlatformRequest::ATTRIBUTE_ACL, $acl);
        
Home | Imprint | This part of the site doesn't use cookies.