Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
23 / 23 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
| AuthMiddleware | |
100.00% |
23 / 23 |
|
100.00% |
2 / 2 |
9 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| process | |
100.00% |
22 / 22 |
|
100.00% |
1 / 1 |
8 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace App\Shared\Security; |
| 6 | |
| 7 | use App\Domain\Auth\Service\Authenticator; |
| 8 | use Psr\Http\Message\ResponseFactoryInterface; |
| 9 | use Psr\Http\Message\ResponseInterface; |
| 10 | use Psr\Http\Message\ServerRequestInterface; |
| 11 | use Psr\Http\Server\MiddlewareInterface; |
| 12 | use Psr\Http\Server\RequestHandlerInterface; |
| 13 | use Yiisoft\Auth\IdentityInterface; |
| 14 | use Yiisoft\Session\SessionInterface; |
| 15 | |
| 16 | class AuthMiddleware implements MiddlewareInterface |
| 17 | { |
| 18 | public const REMEMBER_COOKIE_NAME = 'remember_token'; |
| 19 | |
| 20 | public function __construct( |
| 21 | private SessionInterface $session, |
| 22 | private Authenticator $authenticator, |
| 23 | private ResponseFactoryInterface $responseFactory |
| 24 | ) {} |
| 25 | |
| 26 | public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
| 27 | { |
| 28 | $identity = null; |
| 29 | |
| 30 | if ($this->session->has('user_id')) { |
| 31 | $sessionUserId = $this->session->get('user_id'); |
| 32 | $userId = is_scalar($sessionUserId) ? (string) $sessionUserId : ''; |
| 33 | if ($userId !== '') { |
| 34 | $identity = $this->authenticator->findIdentity($userId); |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | // Proba autologowania przez bezpieczne ciasteczko Remember Me |
| 39 | if ($identity === null) { |
| 40 | $cookies = $request->getCookieParams(); |
| 41 | $rememberToken = (string) ($cookies[self::REMEMBER_COOKIE_NAME] ?? ''); |
| 42 | |
| 43 | if ($rememberToken !== '') { |
| 44 | $identity = $this->authenticator->findIdentityByToken($rememberToken); |
| 45 | if ($identity !== null) { |
| 46 | $this->session->regenerateID(); |
| 47 | $this->session->set('user_id', $identity->getId()); |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | if ($identity === null) { |
| 53 | return $this->responseFactory |
| 54 | ->createResponse(302) |
| 55 | ->withHeader('Location', '/login'); |
| 56 | } |
| 57 | |
| 58 | $request = $request |
| 59 | ->withAttribute(IdentityInterface::class, $identity) |
| 60 | ->withAttribute('user', $identity); |
| 61 | |
| 62 | return $handler->handle($request); |
| 63 | } |
| 64 | } |