Completed
Push — master ( 9a342a...a162ae )
by Andrii
13:06
created

BlacklistMiddleware   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 2
dl 0
loc 45
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A process() 0 9 2
A isForbidden() 0 13 1
A getIp() 0 11 2
1
<?php
2
3
namespace hiapi\Core\Http\Psr15\Middleware;
4
5
use hiapi\exceptions\NotAuthenticatedException;
6
use hiapi\legacy\lib\deps\dbc;
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Psr\Http\Server\MiddlewareInterface;
10
use Psr\Http\Server\RequestHandlerInterface;
11
12
class BlacklistMiddleware implements MiddlewareInterface
13
{
14
    private $dbc;
15
16
    public function __construct(dbc $dbc)
17
    {
18
        $this->dbc = $dbc;
19
    }
20
21
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
22
    {
23
        $ip = $this->getIp($request);
24
        if ($this->isForbidden($ip)) {
25
            throw new NotAuthenticatedException('Forbidden IP: ' . $ip);
26
        }
27
28
        return $handler->handle($request);
29
    }
30
31
    private function isForbidden(string $ip): bool
32
    {
33
        $qip = $this->dbc->quote($ip);
34
        $found = $this->dbc->value("
35
            SELECT      1
36
            FROM        blacklisted
37
            WHERE       client_id = root_client_id()
38
                    AND type_id = ztype_id('blacklisted,ip')
39
                    AND state_id = state_id('blacklisted,ok')
40
                    AND str2inet(name) >>= str2inet($qip)
41
        ");
42
        return (bool)$found;
43
    }
44
45
    private function getIp(ServerRequestInterface $request): string
46
    {
47
        $ip = $request->getAttribute(ClientIpMiddleware::ATTRIBUTE_NAME);
48
        if (!empty($ip)) {
49
            return $ip;
50
        }
51
52
        $params = $request->getServerParams();
53
54
        return $params['REMOTE_ADDR'] ?? '';
55
    }
56
}
57