PR CI / ledger (pull_request) Successful in 4s
PR CI / flow (pull_request) Successful in 5s
PR CI / security (pull_request) Failing after 42s
PR CI / test (lowest) (pull_request) Successful in 48s
PR CI / test (stable) (pull_request) Successful in 49s
PR CI / ui (pull_request) Successful in 53s
PR CI / pr-ci (pull_request) Failing after 1s
PR CI / release-automerge (pull_request) Skipped
57 lines
2.1 KiB
PHP
57 lines
2.1 KiB
PHP
<?php
|
|
|
|
namespace IriksIT\Manager\Modules\Audit;
|
|
|
|
use Closure;
|
|
use Illuminate\Http\Request;
|
|
use IriksIT\Manager\Models\IpBan;
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
|
|
/**
|
|
* Keeps a banned address out of the whole manager, the login page included. It runs ahead of the
|
|
* session and the login, so a banned visitor is not sent round in circles. The answer is written
|
|
* here and not thrown. Alias `manager.not-banned`: put it on the login routes of the host app too.
|
|
*/
|
|
class RefuseBannedAddress
|
|
{
|
|
public function __construct(private readonly IpBans $bans) {}
|
|
|
|
/**
|
|
* @param Closure(Request): Response $next
|
|
*/
|
|
public function handle(Request $request, Closure $next): Response
|
|
{
|
|
$ban = $this->bans->for($request->ip());
|
|
|
|
if ($ban === null) {
|
|
return $next($request);
|
|
}
|
|
|
|
$this->bans->knocked($ban);
|
|
|
|
return self::answer($request, $ban);
|
|
}
|
|
|
|
/** The page (or JSON) a banned address gets, also for a ban on the whole site. */
|
|
public static function answer(Request $request, IpBan $ban): Response
|
|
{
|
|
$where = $ban->whole_site ? __('this site') : __('the manager');
|
|
$message = $ban->expires_at === null
|
|
? __('This address is blocked from :where.', ['where' => $where])
|
|
: __('This address is blocked from :where until :when.', ['where' => $where, 'when' => $ban->expires_at->format('j F Y, H:i')]);
|
|
|
|
// A ban that followed too many attempts is "429 Too Many Requests" and says when to come
|
|
// back; one that was given by hand is a plain "403 Forbidden".
|
|
$status = $ban->automatic ? 429 : 403;
|
|
$headers = ['Cache-Control' => 'no-store'];
|
|
|
|
if ($ban->automatic && $ban->expires_at !== null) {
|
|
$headers['Retry-After'] = (string) max(1, (int) now()->diffInSeconds($ban->expires_at, false));
|
|
}
|
|
|
|
return $request->expectsJson()
|
|
? response()->json(['message' => $message], $status, $headers)
|
|
: response()->view('manager::banned', ['message' => $message, 'status' => $status], $status, $headers);
|
|
}
|
|
}
|