Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
AuthenticatedOnlyMiddleware
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 2
12
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 process
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2
3declare(strict_types=1);
4
5namespace App\Modules\User\Presentation\Middleware;
6
7use Psr\Http\Message\ResponseFactoryInterface;
8use Psr\Http\Message\ResponseInterface;
9use Psr\Http\Message\ServerRequestInterface;
10use Psr\Http\Server\MiddlewareInterface;
11use Psr\Http\Server\RequestHandlerInterface;
12use Yiisoft\User\CurrentUser;
13
14/**
15 * Access Control Middleware for Authenticated Only Routes.
16 *
17 * Redirects guest users to /login when attempting to access protected routes.
18 *
19 * @package App\Modules\User\Presentation\Middleware
20 */
21final readonly class AuthenticatedOnlyMiddleware implements MiddlewareInterface
22{
23    /**
24     * AuthenticatedOnlyMiddleware constructor.
25     *
26     * @param CurrentUser $currentUser Current identity user service instance.
27     * @param ResponseFactoryInterface $responseFactory PSR-7 Response factory.
28     */
29    public function __construct(
30        private CurrentUser $currentUser,
31        private ResponseFactoryInterface $responseFactory
32    ) {
33    }
34
35    /**
36     * {@inheritdoc}
37     */
38    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
39    {
40        if ($this->currentUser->isGuest()) {
41            $response = $this->responseFactory->createResponse(302);
42            return $response->withHeader('Location', '/login');
43        }
44
45        return $handler->handle($request);
46    }
47}