-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathForceHttps.php
More file actions
79 lines (63 loc) · 2.35 KB
/
ForceHttps.php
File metadata and controls
79 lines (63 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?php
declare(strict_types=1);
namespace ForceHttpsModule\Middleware;
use ForceHttpsModule\HttpsTrait;
use Mezzio\Router\RouteResult;
use Mezzio\Router\RouterInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
class ForceHttps implements MiddlewareInterface
{
use HttpsTrait;
/**
* @param mixed[] $config
*/
public function __construct(private array $config, private RouterInterface $router)
{
}
private function setHttpStrictTransportSecurity(
string $uriScheme,
ResponseInterface $response,
RouteResult $routeResult
): ResponseInterface {
if ($this->isSkippedHttpStrictTransportSecurity($uriScheme, $routeResult)) {
return $response;
}
if ($this->config['strict_transport_security']['enable'] === true) {
return $response->withHeader(
'Strict-Transport-Security',
$this->config['strict_transport_security']['value']
);
}
return $response->withHeader('Strict-Transport-Security', 'max-age=0');
}
public function process(
ServerRequestInterface $serverRequest,
RequestHandlerInterface $requestHandler
): ResponseInterface {
$response = $requestHandler->handle($serverRequest);
if (! $this->config['enable']) {
return $response;
}
$match = $this->router->match($serverRequest);
$uri = $serverRequest->getUri();
$uriScheme = $uri->getScheme();
$response = $this->setHttpStrictTransportSecurity($uriScheme, $response, $match);
if (! $this->isGoingToBeForcedToHttps($match)) {
return $response;
}
if ($this->isSchemeHttps($uriScheme)) {
$uriString = $uri->__toString();
$httpsRequestUri = $this->getFinalhttpsRequestUri($uriString);
if ($uriString === $httpsRequestUri) {
return $response;
}
}
$httpsRequestUri ??= $this->getFinalhttpsRequestUri((string) $uri->withScheme('https'));
// 308 keeps headers, request method, and request body
$response = $response->withStatus(308);
return $response->withHeader('Location', $httpsRequestUri);
}
}