1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace TMV\OpenIdClient\Middleware; |
6
|
|
|
|
7
|
|
|
use Dflydev\FigCookies\Cookies; |
8
|
|
|
use Dflydev\FigCookies\FigResponseCookies; |
9
|
|
|
use Dflydev\FigCookies\Modifier\SameSite; |
10
|
|
|
use Dflydev\FigCookies\SetCookie; |
11
|
|
|
use Psr\Http\Message\ResponseInterface; |
12
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
13
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
14
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
15
|
|
|
use TMV\OpenIdClient\Exception\LogicException; |
16
|
|
|
use TMV\OpenIdClient\Model\AuthSession; |
17
|
|
|
use TMV\OpenIdClient\Model\AuthSessionInterface; |
18
|
|
|
|
19
|
|
|
class SessionCookieMiddleware implements MiddlewareInterface |
20
|
|
|
{ |
21
|
|
|
public const SESSION_ATTRIBUTE = AuthSessionInterface::class; |
22
|
|
|
|
23
|
|
|
/** @var string */ |
24
|
|
|
private $cookieName; |
25
|
|
|
|
26
|
|
|
/** @var null|int */ |
27
|
|
|
private $cookieMaxAge; |
28
|
|
|
|
29
|
|
|
public function __construct(string $cookieName = 'openid', ?int $cookieMaxAge = null) |
30
|
|
|
{ |
31
|
|
|
$this->cookieName = $cookieName; |
32
|
|
|
$this->cookieMaxAge = $cookieMaxAge; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
36
|
|
|
{ |
37
|
|
|
if (! \class_exists(Cookies::class)) { |
38
|
|
|
throw new LogicException('To use the SessionCookieMiddleware you should install dflydev/fig-cookies package'); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
$cookies = Cookies::fromRequest($request); |
42
|
|
|
$sessionCookie = $cookies->get($this->cookieName); |
43
|
|
|
|
44
|
|
|
$cookieValue = $sessionCookie ? $sessionCookie->getValue() : null; |
45
|
|
|
$data = $cookieValue ? \json_decode($cookieValue, true) : []; |
46
|
|
|
|
47
|
|
|
if (! \is_array($data)) { |
48
|
|
|
$data = []; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
$authSession = AuthSession::fromArray($data); |
52
|
|
|
|
53
|
|
|
$response = $handler->handle($request->withAttribute(static::SESSION_ATTRIBUTE, $authSession)); |
54
|
|
|
|
55
|
|
|
/** @var string $cookieValue */ |
56
|
|
|
$cookieValue = \json_encode($authSession->jsonSerialize()); |
57
|
|
|
|
58
|
|
|
$sessionCookie = SetCookie::create($this->cookieName) |
59
|
|
|
->withValue($cookieValue) |
60
|
|
|
->withMaxAge($this->cookieMaxAge) |
61
|
|
|
->withHttpOnly() |
62
|
|
|
->withSecure() |
63
|
|
|
->withPath('/') |
64
|
|
|
->withSameSite(SameSite::strict()); |
65
|
|
|
|
66
|
|
|
$response = FigResponseCookies::set($response, $sessionCookie); |
67
|
|
|
|
68
|
|
|
return $response; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|