How could I test my middleware ? Here I am testing if a admin can access a middleware protected route, that returns a 500, if the user does not have a privileged ip - then the middleware returns a 401 (not authorized) when trying to access the /500
page .
My test:
use App\Http\Middleware\OnlyAdminIp;
use Illuminate\Http\Request;
use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class HttpTests extends TestCase
{
use DatabaseTransactions;
/** @test */
public function if_a_500_page_returns_a_500_response_for_admin()
{
$request = Request::create(config('app.url') . '500', 'GET');
$middleware = new OnlyAdminIp();
$response = $middleware->handle($request, function () {});
$this->assertEquals($response->getStatusCode(), 401);
}
}
My middleware:
namespace App\Http\Middleware;
use App\IpList;
use Closure;
class OnlyAdminIp
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$client_ip = $_SERVER["HTTP_CF_CONNECTING_IP"] ?? $request->ip(); // CDN(Cloudflare) provides the real client ip, a safeguard is used to prevent critical error if CDN is removed/changed.
$ipList = IpList::all()
->pluck('ip')
->toArray();
if (!in_array($client_ip, $ipList)) {
abort(401);
}
return $next($request);
}
}
And just for more clarity - the 500 route (in web.php) .
Route::group(['middleware' => 'admin.ip'], function () {
Route::get('500', function () {
abort(500);
});
});
With this setup I am getting Call to a member function getStatusCode() on null
Thanks in advance !
Aucun commentaire:
Enregistrer un commentaire