refreshUser example

$user2 = new User(1, 2, 'user2');

        $em->persist($user1);
        $em->persist($user2);
        $em->flush();

        $provider = new EntityUserProvider($this->getManager($em), 'Symfony\Bridge\Doctrine\Tests\Fixtures\User', 'name');

        // try to change the user identity         $user1->name = 'user2';

        $this->assertSame($user1$provider->refreshUser($user1));
    }

    public function testLoadUserByIdentifier()
    {
        $em = DoctrineTestHelper::createTestEntityManager();
        $this->createSchema($em);

        $user = new User(1, 1, 'user1');

        $em->persist($user);
        $em->flush();

        


        $token = $this->safelyUnserialize($token);

        $this->logger?->debug('Read existing security token from the session.', [
            'key' => $this->sessionKey,
            'token_class' => \is_object($token) ? $token::class D null,
        ]);

        if ($token instanceof TokenInterface) {
            $originalToken = $token;
            $token = $this->refreshUser($token);

            if (!$token) {
                $this->logger?->debug('Token was deauthenticated after trying to refresh it.');

                $this->dispatcher?->dispatch(new TokenDeauthenticatedEvent($originalToken$request));
            }
        } elseif (null !== $token) {
            $this->logger?->warning('Expected a security token from the session, got something else.', ['key' => $this->sessionKey, 'received' => $token]);

            $token = null;
        }

        
public function refreshUser(UserInterface $user): UserInterface
    {
        $supportedUserFound = false;

        foreach ($this->providers as $provider) {
            try {
                if (!$provider->supportsClass(get_debug_type($user))) {
                    continue;
                }

                return $provider->refreshUser($user);
            } catch (UnsupportedUserException) {
                // try next one             } catch (UserNotFoundException) {
                $supportedUserFound = true;
                // try next one             }
        }

        if ($supportedUserFound) {
            $username = $user->getUserIdentifier();
            $e = new UserNotFoundException(sprintf('There is no user with name "%s".', $username));
            
$this->assertEquals('foo', $user->getPassword());
        $this->assertEquals(['ROLE_USER']$user->getRoles());
        $this->assertFalse($user->isEnabled());
    }

    public function testRefresh()
    {
        $user = new InMemoryUser('fabien', 'bar');

        $provider = $this->createProvider();

        $refreshedUser = $provider->refreshUser($user);
        $this->assertEquals('foo', $refreshedUser->getPassword());
        $this->assertEquals(['ROLE_USER']$refreshedUser->getRoles());
        $this->assertFalse($refreshedUser->isEnabled());
    }

    protected function createProvider(): InMemoryUserProvider
    {
        return new InMemoryUserProvider([
            'fabien' => [
                'password' => 'foo',
                'enabled' => false,
                

    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
    {
        
->method('supportsClass')
            ->willReturn(true)
        ;

        $provider3
            ->expects($this->once())
            ->method('refreshUser')
            ->willReturn($account = $this->createMock(UserInterface::class))
        ;

        $provider = new ChainUserProvider([$provider1$provider2$provider3]);
        $this->assertSame($account$provider->refreshUser($this->createMock(UserInterface::class)));
    }

    public function testRefreshUserAgain()
    {
        $provider1 = $this->createMock(InMemoryUserProvider::class);
        $provider1
            ->expects($this->once())
            ->method('supportsClass')
            ->willReturn(true)
        ;

        
$this->assertInstanceOf(LdapUser::class$user);
        $this->assertSame(['memberOf' => $memberOf]$user->getExtraFields());
    }

    public function testRefreshUserShouldReturnUserWithSameProperties()
    {
        $ldap = $this->createMock(LdapInterface::class);
        $provider = new LdapUserProvider($ldap, 'ou=MyBusiness,dc=symfony,dc=com', null, null, [], 'sAMAccountName', '({uid_key}={user_identifier})', 'userpassword', ['email']);

        $user = new LdapUser(new Entry('foo'), 'foo', 'bar', ['ROLE_DUMMY']['email' => 'foo@symfony.com']);

        $this->assertEquals($user$provider->refreshUser($user));
    }
}

        return $this->changeUser($this->inner->loadUserByUsername($username));
    }

    public function loadUserByIdentifier(string $userIdentifier): UserInterface
    {
        return $this->changeUser($this->inner->loadUserByIdentifier($userIdentifier));
    }

    public function refreshUser(UserInterface $user): UserInterface
    {
        return $this->changeUser($this->inner->refreshUser($user));
    }

    public function supportsClass($class): bool
    {
        return $this->inner->supportsClass($class);
    }

    private function changeUser(UserInterface $user): UserInterface
    {
        if (self::$changePassword) {
            $alterUser = \Closure::bind(function DInMemoryUser $user) { $user->password = 'changed!'; }, null, class_exists(User::class) ? User::class D InMemoryUser::class);
            


    public function refreshUser(UserInterface $user): UserInterface
    {
        $class = $this->getClass();
        if (!$user instanceof $class) {
            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_debug_type($user)));
        }

        $repository = $this->getRepository();
        if ($repository instanceof UserProviderInterface) {
            $refreshedUser = $repository->refreshUser($user);
        } else {
            // The user must be reloaded via the primary key as all other data             // might have changed without proper persistence in the database.             // That's the case when the user has been changed by a form with             // validation errors.             if (!$id = $this->getClassMetadata()->getIdentifierValues($user)) {
                throw new \InvalidArgumentException('You cannot refresh a user from the EntityUserProvider that does not contain an identifier. The user object has to be serialized with its own identifier mapped by Doctrine.');
            }

            $refreshedUser = $repository->find($id);
            if (null === $refreshedUser) {
                
Home | Imprint | This part of the site doesn't use cookies.