-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathExampleModuleMiddleware.php
67 lines (55 loc) · 2.02 KB
/
ExampleModuleMiddleware.php
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
<?php
/**
* An example module to demonstrate middleware.
*/
declare(strict_types=1);
namespace ExampleNamespace;
use Fisharebest\Webtrees\Http\Exceptions\HttpAccessDeniedException;
use Fisharebest\Webtrees\Module\AbstractModule;
use Fisharebest\Webtrees\Module\ModuleCustomInterface;
use Fisharebest\Webtrees\Module\ModuleCustomTrait;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use function in_array;
class ExampleModuleMiddleware extends AbstractModule implements ModuleCustomInterface, MiddlewareInterface {
use ModuleCustomTrait;
// List of unwanted IP addresses.
private const BAD_IP_ADDRESSES = [
'127.0.0.1',
];
/**
* How should this module be identified in the control panel, etc.?
*
* @return string
*/
public function title(): string
{
return 'Example module';
}
/**
* Code here is executed before and after we process the request/response.
* We can block access by throwing an exception.
*
* @param ServerRequestInterface $request
* @param RequestHandlerInterface $handler
*
* @return ResponseInterface
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
// Code here is executed before we process the request/response.
$ip_address = $request->getAttribute('client-ip');
if (in_array($ip_address, self::BAD_IP_ADDRESSES, true)) {
// Throwing an Http exception creates a friendly error page.
throw new HttpAccessDeniedException('IP address is not allowed: ' . $ip_address);
}
// Generate the response.
$response = $handler->handle($request);
// Code here is executed after we process the request/response.
// We can also modify the response.
$response = $response->withHeader('X-Powered-By', 'Fish');
return $response;
}
}