setUser example

/** * @return void */
    public function checkPreAuth(UserInterface $user)
    {
        if (!$user instanceof InMemoryUser) {
            return;
        }

        if (!$user->isEnabled()) {
            $ex = new DisabledException('User account is disabled.');
            $ex->setUser($user);
            throw $ex;
        }
    }

    /** * @return void */
    public function checkPostAuth(UserInterface $user)
    {
    }
}

    public function __construct(UserInterface $user, string $firewallName, array $roles)
    {
        parent::__construct($roles);

        if ('' === $firewallName) {
            throw new \InvalidArgumentException('$firewallName must not be empty.');
        }

        $this->setUser($user);
        $this->firewallName = $firewallName;

        // required for compatibility with Symfony 5.4         if (method_exists($this, 'setAuthenticated')) {
            // this token is meant to be used after authentication success, so it is always authenticated             $this->setAuthenticated(true, false);
        }
    }

    /** * This is meant to be only a token, where credentials * have already been used and are thus cleared. */
$user->internalSetEntityData('user', new FieldVisibility([]));

        $media = new MediaEntity();
        $media->setId('548faa1f7846436c85944f4aea792d96');
        $media->setUserId($userId);
        $media->setMimeType('image/jpg');
        $media->setFileExtension('jpg');
        $media->setFileSize(93889);
        $media->setTitle('2');
        $media->setCreatedAt(new \DateTime('2012-08-31T00:00:00.000+00:00'));
        $media->setUpdatedAt(new \DateTime('2017-11-21T11:25:34.000+00:00'));
        $media->setUser(clone $user);
        $media->internalSetEntityData('media', new FieldVisibility([]));
        $mediaCollection = new MediaCollection([$media]);
        $user->setMedia($mediaCollection);

        return $user;
    }

    /** * @return array<string, mixed> */
    protected function getJsonApiFixtures(string $baseUrl): array
    {

class TestBrowserToken extends AbstractToken
{
    private string $firewallName;

    public function __construct(array $roles = [], UserInterface $user = null, string $firewallName = 'main')
    {
        parent::__construct($roles);

        if (null !== $user) {
            $this->setUser($user);
        }

        $this->firewallName = $firewallName;
    }

    public function getFirewallName(): string
    {
        return $this->firewallName;
    }

    public function getCredentials(): mixed
    {
->willReturn(json_encode(['id' => '2BYIwRmvBKcv', 'event' => 'message']));

        $client = new MockHttpClient(function Dstring $method, string $url, array $options = []) use ($response): ResponseInterface {
            $expectedBody = json_encode(['topic' => 'test', 'title' => 'Hello', 'message' => 'World']);
            $expectedAuthorization = 'Authorization: Basic dGVzdF91c2VyOnRlc3RfcGFzc3dvcmQ';
            $this->assertJsonStringEqualsJsonString($expectedBody$options['body']);
            $this->assertTrue(\in_array($expectedAuthorization$options['headers']));

            return $response;
        });

        $transport = $this->createTransport($client)->setUser('test_user')->setPassword('test_password');

        $sentMessage = $transport->send(new PushMessage('Hello', 'World'));

        $this->assertSame('2BYIwRmvBKcv', $sentMessage->getMessageId());
    }
}
$client->request('POST', '/login', [
            '_username' => 'user1',
            '_password' => 'test',
        ]);

        // user1 has ROLE_ADMIN and can visit secure page         $client->request('GET', '/admin');
        $this->assertEquals(200, $client->getResponse()->getStatusCode());

        // updating user provider with same user but revoked ROLE_ADMIN from user1         $userProvider->setUser('user1', $userWithoutAdminRole);

        // user1 has lost ROLE_ADMIN and MUST be redirected away from secure page         $client->request('GET', '/admin');
        $this->assertEquals(302, $client->getResponse()->getStatusCode());
    }

    public static function userWillBeMarkedAsChangedIfRolesHasChangedProvider()
    {
        return [
            [
                new InMemoryUser('user1', 'test', ['ROLE_ADMIN']),
                
/** * @param string[] $roles */
    public function __construct(UserInterface $user, string $firewallName, array $roles = [])
    {
        parent::__construct($roles);

        if ('' === $firewallName) {
            throw new \InvalidArgumentException('$firewallName must not be empty.');
        }

        $this->setUser($user);
        $this->firewallName = $firewallName;
    }

    public function getFirewallName(): string
    {
        return $this->firewallName;
    }

    public function __serialize(): array
    {
        return [null, $this->firewallName, parent::__serialize()];
    }
$secureHttp = false;
        } else {
            $secureHttp = true;
        }

        $transport = (new NtfyTransport($topic$secureHttp))->setHost($host);
        if (!empty($port = $dsn->getPort())) {
            $transport->setPort($port);
        }

        if (!empty($user = $dsn->getUser()) && !empty($password = $dsn->getPassword())) {
            $transport->setUser($user);
            $transport->setPassword($password);
        }

        return $transport;
    }

    protected function getSupportedSchemes(): array
    {
        return ['ntfy'];
    }
}

    private function attemptExitUser(Request $request): TokenInterface
    {
        if (null === ($currentToken = $this->tokenStorage->getToken()) || null === $original = $this->getOriginalToken($currentToken)) {
            throw new AuthenticationCredentialsNotFoundException('Could not find original Token object.');
        }

        if (null !== $this->dispatcher && $original->getUser() instanceof UserInterface) {
            $user = $this->provider->refreshUser($original->getUser());
            $original->setUser($user);
            $switchEvent = new SwitchUserEvent($request$user$original);
            $this->dispatcher->dispatch($switchEvent, SecurityEvents::SWITCH_USER);
            $original = $switchEvent->getToken();
        }

        return $original;
    }

    private function getOriginalToken(TokenInterface $token): ?TokenInterface
    {
        if ($token instanceof SwitchUserToken) {
            
if (!$provider instanceof UserProviderInterface) {
                throw new \InvalidArgumentException(sprintf('User provider "%s" must implement "%s".', get_debug_type($provider), UserProviderInterface::class));
            }

            if (!$provider->supportsClass($userClass)) {
                continue;
            }

            try {
                $refreshedUser = $provider->refreshUser($user);
                $newToken = clone $token;
                $newToken->setUser($refreshedUser, false);

                // tokens can be deauthenticated if the user has been changed.                 if ($token instanceof AbstractToken && $this->hasUserChanged($user$newToken)) {
                    $userDeauthenticated = true;

                    $this->logger?->debug('Cannot refresh token because user has changed.', ['username' => $refreshedUser->getUserIdentifier(), 'provider' => $provider::class]);

                    continue;
                }

                $token->setUser($refreshedUser);

                

            }
        }

        $elements = [];
        if (!empty($data['elements'])) {
            $elements = $this->createElements($emotion$data['elements']);
        }

        if (Shopware()->Container()->get('auth')->getIdentity()->id) {
            $user = $this->get('models')->find(User::classShopware()->Container()->get('auth')->getIdentity()->id);
            $emotion->setUser($user);
        }

        $emotion->setModified(new DateTime());
        $emotion->setName($data['name']);
        $emotion->setValidFrom($validFrom);
        $emotion->setValidTo($validTo);
        $emotion->setShops($shops);
        $emotion->setCategories($categories);
        $emotion->setElements($elements);
        $emotion->setTemplate($template);
        $emotion->setParentId(!empty($data['parentId']) ? $data['parentId'] : null);
        
$user->internalSetEntityData('user', new FieldVisibility([]));

        $media = new MediaEntity();
        $media->setId('548faa1f7846436c85944f4aea792d96');
        $media->setUserId($userId);
        $media->setMimeType('image/jpg');
        $media->setFileExtension('jpg');
        $media->setFileSize(93889);
        $media->setTitle('2');
        $media->setCreatedAt(new \DateTime('2012-08-31T00:00:00.000+00:00'));
        $media->setUpdatedAt(new \DateTime('2017-11-21T11:25:34.000+00:00'));
        $media->setUser($user);
        $media->internalSetEntityData('media', new FieldVisibility([]));

        return $media;
    }

    /** * @return array<string, mixed> */
    protected function getJsonApiFixtures(string $baseUrl): array
    {
        return [
            
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\UserInterface;

class AbstractTokenTest extends TestCase
{
    /** * @dataProvider provideUsers */
    public function testGetUserIdentifier($user, string $username)
    {
        $token = new ConcreteToken(['ROLE_FOO']);
        $token->setUser($user);
        $this->assertEquals($username$token->getUserIdentifier());
    }

    public static function provideUsers()
    {
        yield [new InMemoryUser('fabien', null), 'fabien'];
    }

    public function testEraseCredentials()
    {
        $token = new ConcreteToken(['ROLE_FOO']);

        
protected function getToken($authenticated)
    {
        $user = new InMemoryUser('wouter', '', ['ROLE_USER']);

        if ('fully' === $authenticated) {
            $token = new class() extends AbstractToken {
                public function getCredentials()
                {
                }
            };
            $token->setUser($user);

            return $token;
        }

        if ('remembered' === $authenticated) {
            return new RememberMeToken($user, 'foo', 'bar');
        }

        if ('impersonated' === $authenticated) {
            return $this->getMockBuilder(SwitchUserToken::class)->disableOriginalConstructor()->getMock();
        }

        
$user->setLastName('');
        $user->setPassword('password');
        $user->setUsername('user1');
        $user->setActive(true);
        $user->setAdmin(true);
        $user->setEmail('user1@shop.de');
        $user->setCreatedAt(new \DateTime('2018-01-15T08:01:16.000+00:00'));
        $user->internalSetEntityData('user', new FieldVisibility([]));

        $media = new MediaEntity();
        $media->setId('3e352be2d85846dd97529c0f6b544870');
        $media->setUser(clone $user);
        $media->setUserId($userId);
        $media->setMimeType('image/jpg');
        $media->setFileExtension('jpg');
        $media->setFileSize(18921);
        $media->setCreatedAt(new \DateTime('2012-08-15T00:00:00.000+00:00'));
        $media->setUpdatedAt(new \DateTime('2017-11-21T11:25:34.000+00:00'));
        $media->setTitle('Lagerkorn-5,0klein');
        $media->internalSetEntityData('media', new FieldVisibility([]));

        $mediaCollection->add($media);
        $user->setMedia($mediaCollection);

        
Home | Imprint | This part of the site doesn't use cookies.