2017-11-19 20:05:13 +00:00
|
|
|
<?php
|
|
|
|
|
2018-02-25 21:30:56 +00:00
|
|
|
namespace Pterodactyl\Http\Middleware\Api;
|
2017-11-19 20:05:13 +00:00
|
|
|
|
|
|
|
use IPTools\IP;
|
|
|
|
use IPTools\Range;
|
|
|
|
use Illuminate\Http\Request;
|
2022-06-18 16:04:51 +00:00
|
|
|
use Pterodactyl\Facades\Activity;
|
2022-05-22 18:57:06 +00:00
|
|
|
use Laravel\Sanctum\TransientToken;
|
2017-11-19 20:05:13 +00:00
|
|
|
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
|
|
|
|
|
|
|
|
class AuthenticateIPAccess
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* Determine if a request IP has permission to access the API.
|
|
|
|
*
|
|
|
|
* @throws \Exception
|
|
|
|
* @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
|
|
|
|
*/
|
2022-11-29 17:53:59 +00:00
|
|
|
public function handle(Request $request, \Closure $next): mixed
|
2017-11-19 20:05:13 +00:00
|
|
|
{
|
2022-05-22 18:57:06 +00:00
|
|
|
/** @var \Laravel\Sanctum\TransientToken|\Pterodactyl\Models\ApiKey $token */
|
|
|
|
$token = $request->user()->currentAccessToken();
|
2017-11-19 20:05:13 +00:00
|
|
|
|
2022-05-22 18:57:06 +00:00
|
|
|
// If this is a stateful request just push the request through to the next
|
|
|
|
// middleware in the stack, there is nothing we need to explicitly check. If
|
|
|
|
// this is a valid API Key, but there is no allowed IP restriction, also pass
|
|
|
|
// the request through.
|
|
|
|
if ($token instanceof TransientToken || empty($token->allowed_ips)) {
|
2017-11-19 20:05:13 +00:00
|
|
|
return $next($request);
|
|
|
|
}
|
|
|
|
|
2017-11-26 19:26:38 +00:00
|
|
|
$find = new IP($request->ip());
|
2022-05-22 18:57:06 +00:00
|
|
|
foreach ($token->allowed_ips as $ip) {
|
2017-11-26 19:26:38 +00:00
|
|
|
if (Range::parse($ip)->contains($find)) {
|
2017-11-19 20:05:13 +00:00
|
|
|
return $next($request);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-18 16:04:51 +00:00
|
|
|
Activity::event('auth:ip-blocked')
|
|
|
|
->actor($request->user())
|
|
|
|
->subject($request->user(), $token)
|
|
|
|
->property('identifier', $token->identifier)
|
|
|
|
->log();
|
|
|
|
|
2018-03-01 05:39:59 +00:00
|
|
|
throw new AccessDeniedHttpException('This IP address (' . $request->ip() . ') does not have permission to access the API using these credentials.');
|
2017-11-19 20:05:13 +00:00
|
|
|
}
|
|
|
|
}
|