0 follower

Final Class Yiisoft\User\Login\Cookie\CookieLoginMiddleware

InheritanceYiisoft\User\Login\Cookie\CookieLoginMiddleware
ImplementsPsr\Http\Server\MiddlewareInterface

CookieLoginMiddleware automatically logs user in based on cookie.

Method Details

Hide inherited methods

__construct() public method

public __construct( Yiisoft\User\CurrentUser $currentUser, \Yiisoft\Auth\IdentityRepositoryInterface $identityRepository, \Psr\Log\LoggerInterface $logger, Yiisoft\User\Login\Cookie\CookieLogin $cookieLogin, boolean $forceAddCookie false ): mixed
$currentUser Yiisoft\User\CurrentUser

The current user instance.

$identityRepository \Yiisoft\Auth\IdentityRepositoryInterface

The identity repository instance.

$logger \Psr\Log\LoggerInterface

The logger instance.

$cookieLogin Yiisoft\User\Login\Cookie\CookieLogin

The cookie login instance.

$forceAddCookie boolean

Whether to force add a cookie.

                public function __construct(
    private CurrentUser $currentUser,
    private IdentityRepositoryInterface $identityRepository,
    private LoggerInterface $logger,
    private CookieLogin $cookieLogin,
    private bool $forceAddCookie = false
) {
}

            
process() public method

public process( \Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Server\RequestHandlerInterface $handler ):
$request \Psr\Http\Message\ServerRequestInterface
$handler \Psr\Http\Server\RequestHandlerInterface
throws JsonException

If an error occurs when JSON encoding the cookie value while adding the cookie file.

throws RuntimeException

If during authentication, the identity repository \Yiisoft\Auth\IdentityRepositoryInterface does not return an instance of Yiisoft\User\Login\Cookie\CookieLoginIdentityInterface.

                public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
    if ($this->currentUser->isGuest()) {
        $this->authenticateUserByCookieFromRequest($request);
    }
    $guestBeforeHandle = $this->currentUser->isGuest();
    $response = $handler->handle($request);
    $guestAfterHandle = $this->currentUser->isGuest();
    if ($this->forceAddCookie && $guestBeforeHandle && !$guestAfterHandle) {
        $identity = $this->currentUser->getIdentity();
        if ($identity instanceof CookieLoginIdentityInterface) {
            $response = $this->cookieLogin->addCookie($identity, $response);
        }
    }
    if (!$guestBeforeHandle && $guestAfterHandle) {
        $response = $this->cookieLogin->expireCookie($response);
    }
    return $response;
}