1 | <?php |
||
8 | class BearerTokenAuthorization implements ApiAuthorizationInterface |
||
9 | { |
||
10 | /** |
||
11 | * @var BearerTokenRepositoryInterface |
||
12 | */ |
||
13 | private $tokenRepository; |
||
14 | |||
15 | /** |
||
16 | * @var string|null |
||
17 | */ |
||
18 | private $errorMessage = null; |
||
19 | |||
20 | /** |
||
21 | * @var IpDetectorInterface |
||
22 | */ |
||
23 | private $ipDetector; |
||
24 | |||
25 | /** |
||
26 | * BearerTokenAuthorization constructor. |
||
27 | * |
||
28 | * @param BearerTokenRepositoryInterface $tokenRepository |
||
29 | * @param IpDetectorInterface $ipDetector |
||
30 | */ |
||
31 | 33 | public function __construct(BearerTokenRepositoryInterface $tokenRepository, IpDetectorInterface $ipDetector) |
|
36 | |||
37 | /** |
||
38 | * {@inheritdoc} |
||
39 | */ |
||
40 | 33 | public function authorized(): bool |
|
60 | |||
61 | /** |
||
62 | * {@inheritdoc} |
||
63 | */ |
||
64 | 18 | public function getErrorMessage(): ?string |
|
68 | |||
69 | /** |
||
70 | * Check if actual IP from detector satisfies @ipRestristions |
||
71 | * $ipRestrictions should contains multiple formats: |
||
72 | * '*' - accessible from anywhare |
||
73 | * '127.0.0.1' - accessible from single IP |
||
74 | * '127.0.0.1,127.0.02' - accessible from multiple IP, separator could be new line or space |
||
75 | * '127.0.0.1/32' - accessible from ip range |
||
76 | * null - disabled access |
||
77 | * |
||
78 | * @return boolean |
||
79 | */ |
||
80 | 18 | private function isValidIp(?string $ipRestrictions): bool |
|
81 | { |
||
82 | 18 | if ($ipRestrictions === null) { |
|
83 | 3 | return false; |
|
84 | } |
||
85 | 15 | if ($ipRestrictions === '*' || $ipRestrictions === '') { |
|
86 | 3 | return true; |
|
87 | } |
||
88 | 12 | $ip = $this->ipDetector->getRequestIp(); |
|
89 | |||
90 | 12 | $ipWhiteList = str_replace([',', ' ', "\n"], '#', $ipRestrictions); |
|
91 | 12 | $ipWhiteList = explode('#', $ipWhiteList); |
|
92 | 12 | foreach ($ipWhiteList as $whiteIp) { |
|
93 | 12 | if ($whiteIp === $ip) { |
|
94 | 6 | return true; |
|
95 | } |
||
96 | 9 | if (strpos($whiteIp, '/') !== false) { |
|
97 | 7 | return $this->ipInRange($ip, $whiteIp); |
|
98 | } |
||
99 | } |
||
100 | |||
101 | 6 | return false; |
|
102 | } |
||
103 | |||
104 | /** |
||
105 | * Check if IP is in $range |
||
106 | * |
||
107 | * @param string $ip this ip will be verified |
||
108 | * @param string $range is in IP/CIDR format eg 127.0.0.1/24 |
||
109 | * @return boolean |
||
110 | */ |
||
111 | 3 | private function ipInRange(string $ip, string $range): bool |
|
120 | |||
121 | /** |
||
122 | * Read HTTP reader with authorization token |
||
123 | * If everything is ok, it return token. In other situations returns false and set errorMessage. |
||
124 | * |
||
125 | * @return string|null |
||
126 | */ |
||
127 | 33 | private function readAuthorizationToken(): ?string |
|
144 | } |
||
145 |