Completed
Pull Request — master (#9)
by
unknown
03:37
created

IpAddressOrUserIdentityResolver   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
B getIdentity() 0 25 8
1
<?php
2
/**
3
 * This file is part of the Rate Limit package.
4
 *
5
 * Copyright (c) Nikola Posa
6
 *
7
 * For full copyright and license information, please refer to the LICENSE file,
8
 * located at the package root folder.
9
 */
10
11
declare(strict_types=1);
12
13
namespace RateLimit\Middleware\Identity;
14
15
use Psr\Http\Message\RequestInterface;
16
use Psr\Http\Message\ServerRequestInterface;
17
18
/**
19
 * @author Vassilis Poursalidis <[email protected]>
20
 */
21
final class IpAddressOrUserIdentityResolver extends AbstractIdentityResolver
22
{
23
    const IP_KEY_PREFIX   = 'rlimit-ip-';
24
    const USER_KEY_PREFIX = 'rlimit-id-';
25
26
    /**
27
     * @var array
28
     */
29
    protected $loadBalancers;
30
31
    /**
32
     * @var string
33
     */
34
    protected $authKeyName;
35
36
    public function __construct(array $loadBalancers = [], string $authKeyName = 'authUserId')
37
    {
38
        $this->loadBalancers = $loadBalancers;
39
        $this->authKeyName   = $authKeyName;
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function getIdentity(RequestInterface $request) : string
46
    {
47
        if (!$request instanceof ServerRequestInterface) {
48
            return self::getDefaultIdentity($request);
49
        }
50
51
        $serverParams = $request->getServerParams();
52
        $authUserId   = $request->getAttribute($this->authKeyName);
53
54
        if ( !empty($authUserId) ) {
55
            return USER_KEY_PREFIX . $authUserId;
56
        }
57
58
        if ( !empty($serverParams['REMOTE_ADDR']) && in_array($serverParams['REMOTE_ADDR'], $this->loadBalancers) ) {
59
            if (array_key_exists('HTTP_CLIENT_IP', $serverParams)) {
60
                return self::IP_KEY_PREFIX . $serverParams['HTTP_CLIENT_IP'];
61
            }
62
63
            if (array_key_exists('HTTP_X_FORWARDED_FOR', $serverParams)) {
64
                return self::IP_KEY_PREFIX . $serverParams['HTTP_X_FORWARDED_FOR'];
65
            }
66
        }
67
68
        return $serverParams['REMOTE_ADDR'] ? (self::IP_KEY_PREFIX . $serverParams['REMOTE_ADDR']) : self::getDefaultIdentity($request);
69
    }
70
}
71