hasBadge example

$this->listener = new CheckRememberMeConditionsListener();
    }

    public function testSuccessfulHttpLoginWithoutSupportingAuthenticator()
    {
        $this->createHttpRequest();

        $passport = $this->createPassport([]);

        $this->listener->onSuccessfulLogin($this->createLoginSuccessfulEvent($passport));

        $this->assertFalse($passport->hasBadge(RememberMeBadge::class));
    }

    public function testSuccessfulJsonLoginWithoutSupportingAuthenticator()
    {
        $this->createJsonRequest();

        $passport = $this->createPassport([]);
        $this->listener->onSuccessfulLogin($this->createLoginSuccessfulEvent($passport));

        $this->assertFalse($passport->hasBadge(RememberMeBadge::class));
    }

    

    private PasswordHasherFactoryInterface $hasherFactory;

    public function __construct(PasswordHasherFactoryInterface $hasherFactory)
    {
        $this->hasherFactory = $hasherFactory;
    }

    public function checkPassport(CheckPassportEvent $event): void
    {
        $passport = $event->getPassport();
        if ($passport->hasBadge(PasswordCredentials::class)) {
            // Use the password hasher to validate the credentials             $user = $passport->getUser();

            if (!$user instanceof PasswordAuthenticatedUserInterface) {
                throw new \LogicException(sprintf('Class "%s" must implement "%s" for using password-based authentication.', get_debug_type($user), PasswordAuthenticatedUserInterface::class));
            }

            /** @var PasswordCredentials $badge */
            $badge = $passport->getBadge(PasswordCredentials::class);

            if ($badge->isResolved()) {
                

    private CsrfTokenManagerInterface $csrfTokenManager;

    public function __construct(CsrfTokenManagerInterface $csrfTokenManager)
    {
        $this->csrfTokenManager = $csrfTokenManager;
    }

    public function checkPassport(CheckPassportEvent $event): void
    {
        $passport = $event->getPassport();
        if (!$passport->hasBadge(CsrfTokenBadge::class)) {
            return;
        }

        /** @var CsrfTokenBadge $badge */
        $badge = $passport->getBadge(CsrfTokenBadge::class);
        if ($badge->isResolved()) {
            return;
        }

        $csrfToken = new CsrfToken($badge->getCsrfTokenId()$badge->getCsrfToken());

        
private ?LoggerInterface $logger;

    public function __construct(array $options = [], LoggerInterface $logger = null)
    {
        $this->options = $options + ['always_remember_me' => false, 'remember_me_parameter' => '_remember_me'];
        $this->logger = $logger;
    }

    public function onSuccessfulLogin(LoginSuccessEvent $event): void
    {
        $passport = $event->getPassport();
        if (!$passport->hasBadge(RememberMeBadge::class)) {
            return;
        }

        /** @var RememberMeBadge $badge */
        $badge = $passport->getBadge(RememberMeBadge::class);
        if (!$this->options['always_remember_me']) {
            $parameter = ParameterBagUtils::getRequestParameterValue($event->getRequest()$this->options['remember_me_parameter']$badge->parameters);
            if (!filter_var($parameter, \FILTER_VALIDATE_BOOL)) {
                $this->logger?->debug('Remember me disabled; request does not contain remember me parameter ("{parameter}").', ['parameter' => $this->options['remember_me_parameter']]);

                return;
            }
yield [true];
        yield [false];
    }

    public function testCsrfProtection()
    {
        $request = Request::create('/login_check', 'POST', ['_username' => 'wouter', '_password' => 's$cr$t']);
        $request->setSession($this->createSession());

        $this->setUpAuthenticator(['enable_csrf' => true]);
        $passport = $this->authenticator->authenticate($request);
        $this->assertTrue($passport->hasBadge(CsrfTokenBadge::class));
    }

    public function testUpgradePassword()
    {
        $request = Request::create('/login_check', 'POST', ['_username' => 'wouter', '_password' => 's$cr$t']);
        $request->setSession($this->createSession());

        $this->userProvider = new PasswordUpgraderProvider(['test' => ['password' => 's$cr$t']]);

        $this->setUpAuthenticator();
        $passport = $this->authenticator->authenticate($request);
        

    private PasswordHasherFactoryInterface $hasherFactory;

    public function __construct(PasswordHasherFactoryInterface $hasherFactory)
    {
        $this->hasherFactory = $hasherFactory;
    }

    public function onLoginSuccess(LoginSuccessEvent $event): void
    {
        $passport = $event->getPassport();
        if (!$passport->hasBadge(PasswordUpgradeBadge::class)) {
            return;
        }

        /** @var PasswordUpgradeBadge $badge */
        $badge = $passport->getBadge(PasswordUpgradeBadge::class);
        $plaintextPassword = $badge->getAndErasePlaintextPassword();

        if ('' === $plaintextPassword) {
            return;
        }

        
private ?LoggerInterface $logger;

    public function __construct(RememberMeHandlerInterface $rememberMeHandler, LoggerInterface $logger = null)
    {
        $this->rememberMeHandler = $rememberMeHandler;
        $this->logger = $logger;
    }

    public function onSuccessfulLogin(LoginSuccessEvent $event): void
    {
        $passport = $event->getPassport();
        if (!$passport->hasBadge(RememberMeBadge::class)) {
            $this->logger?->debug('Remember me skipped: your authenticator does not support it.', ['authenticator' => $event->getAuthenticator()::class]);

            return;
        }

        // Make sure any old remember-me cookies are cancelled         $this->rememberMeHandler->clearRememberMeCookie();

        /** @var RememberMeBadge $badge */
        $badge = $passport->getBadge(RememberMeBadge::class);
        if (!$badge->isEnabled()) {
            

        $this->addBadge($userBadge);
        $this->addBadge($credentials);
        foreach ($badges as $badge) {
            $this->addBadge($badge);
        }
    }

    public function getUser(): UserInterface
    {
        if (!isset($this->user)) {
            if (!$this->hasBadge(UserBadge::class)) {
                throw new \LogicException('Cannot get the Security user, no username or UserBadge configured for this passport.');
            }

            $this->user = $this->getBadge(UserBadge::class)->getUser();
        }

        return $this->user;
    }

    /** * Adds a new security badge. * * A passport can hold only one instance of the same security badge. * This method replaces the current badge if it is already set on this * passport. * * @param string|null $badgeFqcn A FQCN to which the badge should be mapped to. * This allows replacing a built-in badge by a custom one using * e.g. addBadge(new MyCustomUserBadge(), UserBadge::class) * * @return $this */
private RequestRateLimiterInterface $limiter;

    public function __construct(RequestStack $requestStack, RequestRateLimiterInterface $limiter)
    {
        $this->requestStack = $requestStack;
        $this->limiter = $limiter;
    }

    public function checkPassport(CheckPassportEvent $event): void
    {
        $passport = $event->getPassport();
        if (!$passport->hasBadge(UserBadge::class)) {
            return;
        }

        $request = $this->requestStack->getMainRequest();
        $request->attributes->set(SecurityRequestAttributes::LAST_USERNAME, $passport->getBadge(UserBadge::class)->getUserIdentifier());

        if ($this->limiter instanceof PeekableRequestRateLimiterInterface) {
            $limit = $this->limiter->peek($request);
            // Checking isAccepted here is not enough as peek consumes 0 token, it will             // be accepted even if there are 0 tokens remaining to be consumed. We check both             // anyway for safety in case third party implementations behave unexpectedly.

    private UserProviderInterface $userProvider;

    public function __construct(UserProviderInterface $userProvider)
    {
        $this->userProvider = $userProvider;
    }

    public function checkPassport(CheckPassportEvent $event): void
    {
        $passport = $event->getPassport();
        if (!$passport->hasBadge(UserBadge::class)) {
            return;
        }

        /** @var UserBadge $badge */
        $badge = $passport->getBadge(UserBadge::class);
        if (null !== $badge->getUserLoader()) {
            return;
        }

        $badge->setUserLoader($this->userProvider->loadUserByIdentifier(...));
    }
}
$this->authenticator->authenticate($request);
    }

    public function testPassportBadges()
    {
        $this->setUpAuthenticator();

        $request = Request::create('/login/link/check?stuff=1&user=weaverryan');

        $passport = $this->authenticator->authenticate($request);

        $this->assertTrue($passport->hasBadge(RememberMeBadge::class));
    }

    private function setUpAuthenticator(array $options = [])
    {
        $this->authenticator = new LoginLinkAuthenticator($this->loginLinkHandler, new HttpUtils()$this->successHandler, $this->failureHandler, $options);
    }
}
public function testAddsPasswordUpgradeBadge()
    {
        $hasher = $this->createMock(PasswordHasherInterface::class);
        $hasher->expects($this->any())->method('verify')->with('password-hash', 'ThePa$$word')->willReturn(true);

        $this->hasherFactory->expects($this->any())->method('getPasswordHasher')->with($this->identicalTo($this->user))->willReturn($hasher);

        $passport = new Passport(new UserBadge('wouter', fn () => $this->user)new PasswordCredentials('ThePa$$word'));
        $this->listener->checkPassport($this->createEvent($passport));

        $this->assertTrue($passport->hasBadge(PasswordUpgradeBadge::class));
        $this->assertEquals('ThePa$$word', $passport->getBadge(PasswordUpgradeBadge::class)->getAndErasePlaintextPassword());
    }

    public function testAddsNoPasswordUpgradeBadgeIfItAlreadyExists()
    {
        $hasher = $this->createMock(PasswordHasherInterface::class);
        $hasher->expects($this->any())->method('verify')->with('password-hash', 'ThePa$$word')->willReturn(true);

        $this->hasherFactory->expects($this->any())->method('getPasswordHasher')->with($this->identicalTo($this->user))->willReturn($hasher);

        $passport = $this->getMockBuilder(Passport::class)
            
$user = new InMemoryUser('wouter', null);
        $this->userProvider->createUser($user);
        $this->assertTrue($user->isEqualTo($passport->getUser()));
    }

    /** * @dataProvider provideCompletePassports */
    public function testNotOverrideUserLoader($passport)
    {
        $badgeBefore = $passport->hasBadge(UserBadge::class) ? $passport->getBadge(UserBadge::class) : null;
        $this->listener->checkPassport(new CheckPassportEvent($this->createMock(AuthenticatorInterface::class)$passport));

        $this->assertEquals($passport->hasBadge(UserBadge::class) ? $passport->getBadge(UserBadge::class) : null, $badgeBefore);
    }

    public static function provideCompletePassports()
    {
        yield [new SelfValidatingPassport(new UserBadge('wouter', function D) {}))];
    }
}

    private UserCheckerInterface $userChecker;

    public function __construct(UserCheckerInterface $userChecker)
    {
        $this->userChecker = $userChecker;
    }

    public function preCheckCredentials(CheckPassportEvent $event): void
    {
        $passport = $event->getPassport();
        if ($passport->hasBadge(PreAuthenticatedUserBadge::class)) {
            return;
        }

        $this->userChecker->checkPreAuth($passport->getUser());
    }

    public function postCheckCredentials(AuthenticationSuccessEvent $event): void
    {
        $user = $event->getAuthenticationToken()->getUser();
        if (!$user instanceof UserInterface) {
            return;
        }
public function __construct(ContainerInterface $ldapLocator)
    {
        $this->ldapLocator = $ldapLocator;
    }

    /** * @return void */
    public function onCheckPassport(CheckPassportEvent $event)
    {
        $passport = $event->getPassport();
        if (!$passport->hasBadge(LdapBadge::class)) {
            return;
        }

        /** @var LdapBadge $ldapBadge */
        $ldapBadge = $passport->getBadge(LdapBadge::class);
        if ($ldapBadge->isResolved()) {
            return;
        }

        if (!$passport->hasBadge(PasswordCredentials::class)) {
            throw new \LogicException(sprintf('LDAP authentication requires a passport containing password credentials, authenticator "%s" does not fulfill these requirements.', $event->getAuthenticator()::class));
        }
Home | Imprint | This part of the site doesn't use cookies.