Skip to content

Commit 8198c22

Browse files
committed
use PSR-7 for IP address middleware
1 parent d2a08f4 commit 8198c22

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

src/Tqdev/PhpCrudApi/Middleware/IpAddressMiddleware.php

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,15 +22,15 @@ public function __construct(Router $router, Responder $responder, array $propert
2222
$this->reflection = $reflection;
2323
}
2424

25-
private function callHandler($record, string $operation, ReflectedTable $table) /*: object */
25+
private function callHandler(ServerRequestInterface $request, $record, string $operation, ReflectedTable $table) /*: object */
2626
{
2727
$context = (array) $record;
2828
$columnNames = $this->getProperty('columns', '');
2929
if ($columnNames) {
3030
foreach (explode(',', $columnNames) as $columnName) {
3131
if ($table->hasColumn($columnName)) {
3232
if ($operation == 'create') {
33-
$context[$columnName] = $_SERVER['REMOTE_ADDR'];
33+
$context[$columnName] = $this->getIpAddress($request);
3434
} else {
3535
unset($context[$columnName]);
3636
}
@@ -40,6 +40,18 @@ private function callHandler($record, string $operation, ReflectedTable $table)
4040
return (object) $context;
4141
}
4242

43+
private function getIpAddress(ServerRequestInterface $request): string
44+
{
45+
$reverseProxy = $this->getProperty('reverseProxy', '');
46+
if ($reverseProxy) {
47+
$ipAddress = array_pop($request->getHeader('X-Forwarded-For'));
48+
} else {
49+
$serverParams = $request->getServerParams();
50+
$ipAddress = $serverParams['REMOTE_ADDR'] ?? '127.0.0.1';
51+
}
52+
return $ipAddress;
53+
}
54+
4355
public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
4456
{
4557
$operation = RequestUtils::getOperation($request);
@@ -53,10 +65,10 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface
5365
$table = $this->reflection->getTable($tableName);
5466
if (is_array($record)) {
5567
foreach ($record as &$r) {
56-
$r = $this->callHandler($r, $operation, $table);
68+
$r = $this->callHandler($request, $r, $operation, $table);
5769
}
5870
} else {
59-
$record = $this->callHandler($record, $operation, $table);
71+
$record = $this->callHandler($request, $record, $operation, $table);
6072
}
6173
$request = $request->withParsedBody($record);
6274
}

0 commit comments

Comments
 (0)