xref: /webtrees/app/Http/Middleware/ClientIp.php (revision 5afbc57a5c33b9caec67458db57f44e54a90f745)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2019 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17declare(strict_types=1);
18
19namespace Fisharebest\Webtrees\Http\Middleware;
20
21use Psr\Http\Message\ResponseInterface;
22use Psr\Http\Message\ServerRequestInterface;
23use Psr\Http\Server\RequestHandlerInterface;
24
25use function explode;
26
27/**
28 * Middleware to detect the client's IP address.
29 */
30class ClientIp extends \Middlewares\ClientIp
31{
32    /**
33     * @param ServerRequestInterface  $request
34     * @param RequestHandlerInterface $handler
35     *
36     * @return ResponseInterface
37     */
38    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
39    {
40        // The configuration comes from config.ini.php, via request attributes.
41        $trusted_headers = $this->getCommaSeparatedAttribute($request, 'trusted_headers');
42        $trusted_proxies = $this->getCommaSeparatedAttribute($request, 'trusted_proxies');
43
44        $this->proxy($trusted_proxies, $trusted_headers);
45
46        return parent::process($request, $handler);
47    }
48
49    /**
50     * @param ServerRequestInterface $request
51     * @param string                 $attribute
52     *
53     * @return string[]
54     */
55    private function getCommaSeparatedAttribute(ServerRequestInterface $request, string $attribute): array
56    {
57        $value = $request->getAttribute($attribute);
58
59        if ($value === null) {
60            return [];
61        }
62
63        return explode(',', $value);
64    }
65}
66